-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
112 lines (99 loc) · 2.32 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"GoRPC/gorpc"
"GoRPC/registry"
"GoRPC/xclient"
"context"
"log"
"net"
"net/http"
"sync"
"time"
)
type Foo int
type Args struct{Num1,Num2 int}
func (f Foo) Sum(args Args,reply *int) error{
*reply = args.Num1 + args.Num2
return nil
}
func (f Foo) Sleep(args Args,reply *int) error{
time.Sleep(time.Second * time.Duration(args.Num1))
*reply = args.Num2 + args.Num1
return nil
}
func startRegistry(wg *sync.WaitGroup){
l,_ := net.Listen("tcp",":3080")
registry.HandleHTTP()
wg.Done()
http.Serve(l,nil)
}
func startServer(registryAddr string,wg *sync.WaitGroup){
var foo Foo
l,_ := net.Listen("tcp",":0")
server := gorpc.NewServer()
server.Register(&foo)
registry.Heartbeat(registryAddr,"tcp@"+l.Addr().String(),0)
wg.Done()
server.Accept(l)
}
func foo(xc *xclient.XClient,ctx context.Context,typ,serviceMethod string,args *Args){
var reply int
var err error
switch typ {
case "call":
err = xc.Call(ctx,serviceMethod,args,&reply)
case "broadcast":
err = xc.Broadcast(ctx,serviceMethod,args,&reply)
}
if err != nil{
log.Printf("%s %s error: %v",typ,serviceMethod,err)
}else{
log.Printf("%s %s success: %d + %d = %d",typ,serviceMethod,args.Num1,args.Num2,reply)
}
}
func call(registry string){
d := xclient.NewGoRegistryDiscovery(registry,0)
xc := xclient.NewXClient(d,xclient.RandomSelect,nil)
defer func(){xc.Close()}()
var wg sync.WaitGroup
for i:=0;i<5;i++{
wg.Add(1)
go func(i int){
defer wg.Done()
foo(xc,context.Background(),"call","Foo.Sum",&Args{i,i*i})
}(i)
}
wg.Wait()
}
func broadcast(registry string){
d := xclient.NewGoRegistryDiscovery(registry,0)
xc := xclient.NewXClient(d,xclient.RandomSelect,nil)
defer func(){xc.Close()}()
var wg sync.WaitGroup
for i:=0;i<5;i++{
wg.Add(1)
go func(i int){
defer wg.Done()
foo(xc,context.Background(),"broadcast","Foo.Sum",&Args{i,i*i})
ctx,_:= context.WithTimeout(context.Background(),time.Second*2)
foo(xc,ctx,"broadcast","Foo.Sleep",&Args{i,i*i})
}(i)
}
wg.Wait()
}
func main(){
log.SetFlags(0)
registryAddr := "http://localhost:3080/_gorpc_/registry"
var wg sync.WaitGroup
wg.Add(1)
go startRegistry(&wg)
wg.Wait()
time.Sleep(time.Second)
wg.Add(2)
go startServer(registryAddr,&wg)
go startServer(registryAddr,&wg)
wg.Wait()
time.Sleep(time.Second)
call(registryAddr)
broadcast(registryAddr)
}