-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
executable file
·118 lines (100 loc) · 2.22 KB
/
server.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
113
114
115
116
117
/*
* Copyright (c) 2018, https://github.com/airwide-code/airwide.datacenter
* All rights reserved.
*
*
*
*/
package main
import (
"flag"
"fmt"
"github.com/coreos/etcd/clientv3"
"github.com/airwide-code/airwide.datacenter/baselib/grpc_util/service_discovery/examples/proto"
"github.com/airwide-code/airwide.datacenter/baselib/grpc_util/service_discovery/etcd3"
"golang.org/x/net/context"
"google.golang.org/grpc"
"log"
"net"
"sync"
// "time"
)
var nodeID = flag.String("node", "node1", "node ID")
var port = flag.Int("port", 8080, "listening port")
type RpcServer struct {
addr string
s *grpc.Server
}
func NewRpcServer(addr string) *RpcServer {
s := grpc.NewServer()
rs := &RpcServer{
addr: addr,
s: s,
}
return rs
}
func (s *RpcServer) Run() {
listener, err := net.Listen("tcp", s.addr)
if err != nil {
log.Printf("failed to listen: %v", err)
return
}
log.Printf("rpc listening on:%s", s.addr)
proto.RegisterEchoServiceServer(s.s, s)
s.s.Serve(listener)
}
func (s *RpcServer) Stop() {
s.s.GracefulStop()
}
func (s *RpcServer) Echo(ctx context.Context, req *proto.EchoReq) (*proto.EchoRsp, error) {
text := "Hello " + req.EchoData + ", I am " + *nodeID
log.Println(text)
return &proto.EchoRsp{EchoData: text}, nil
}
func StartService() {
etcdConfg := clientv3.Config{
Endpoints: []string{"http://127.0.0.1:2379"},
}
registry, err := etcd3.NewRegistry(
etcd3.Option{
EtcdConfig: etcdConfg,
RegistryDir: "/grpc-lb",
ServiceName: "test",
NodeID: *nodeID,
NData: etcd3.NodeData{
Addr: fmt.Sprintf("127.0.0.1:%d", *port),
//Metadata: map[string]string{"weight": "1"},
},
Ttl: 10, // * time.Second,
})
if err != nil {
log.Panic(err)
return
}
server := NewRpcServer(fmt.Sprintf("0.0.0.0:%d", *port))
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
server.Run()
wg.Done()
}()
wg.Add(1)
go func() {
registry.Register()
wg.Done()
}()
//stop the server after one minute
//go func() {
// time.Sleep(time.Minute)
// server.Stop()
// registry.Deregister()
//}()
wg.Wait()
}
//go run server.go -node node1 -port 28544
//go run server.go -node node2 -port 18562
//go run server.go -node node3 -port 27772
func main() {
flag.Parse()
StartService()
}