github.com/glide-im/glide@v1.6.0/pkg/rpc/client.go (about) 1 package rpc 2 3 import ( 4 "context" 5 "fmt" 6 "github.com/glide-im/glide/pkg/logger" 7 etcd "github.com/rpcxio/rpcx-etcd/client" 8 "github.com/smallnest/rpcx/client" 9 "github.com/smallnest/rpcx/protocol" 10 ) 11 12 type Cli interface { 13 Call(ctx context.Context, fn string, request, reply interface{}) error 14 Broadcast(fn string, request, reply interface{}) error 15 Run() error 16 Close() error 17 } 18 19 type ClientOptions struct { 20 client.Option 21 22 Addr string 23 Port int 24 Name string 25 EtcdServers []string 26 Selector client.Selector 27 } 28 29 type BaseClient struct { 30 cli client.XClient 31 options *ClientOptions 32 id string 33 } 34 35 func NewBaseClient(options *ClientOptions) (*BaseClient, error) { 36 ret := &BaseClient{ 37 options: options, 38 } 39 40 var discovery client.ServiceDiscovery 41 var err error 42 43 if options.EtcdServers != nil { 44 discovery, err = etcd.NewEtcdV3Discovery(BaseServicePath, options.Name, options.EtcdServers, false, nil) 45 if err != nil { 46 return nil, err 47 } 48 } else { 49 srv := fmt.Sprintf("%s@%s:%d", "tcp", options.Addr, options.Port) 50 discovery, _ = client.NewPeer2PeerDiscovery(srv, "") 51 } 52 53 if options.SerializeType == protocol.SerializeNone { 54 // using protobuffer serializer by default 55 options.SerializeType = protocol.ProtoBuffer 56 } 57 ret.cli = client.NewXClient(options.Name, client.Failtry, client.RoundRobin, discovery, options.Option) 58 59 if options.Selector != nil { 60 ret.cli.SetSelector(options.Selector) 61 } else { 62 // using round robbin selector by default 63 ret.cli.SetSelector(NewRoundRobinSelector()) 64 } 65 return ret, nil 66 } 67 68 func (c *BaseClient) Call2(fn string, arg interface{}, reply interface{}) error { 69 return c.Call(context.Background(), fn, arg, reply) 70 } 71 72 func (c *BaseClient) Broadcast(fn string, request, reply interface{}) error { 73 return c.cli.Broadcast(context.Background(), fn, request, reply) 74 } 75 76 func (c *BaseClient) Call(ctx context.Context, fn string, arg interface{}, reply interface{}) error { 77 logger.D("rpc call %s, args=%v", fn, arg) 78 err := c.cli.Call(ctx, fn, arg, reply) 79 return err 80 } 81 82 func (c *BaseClient) Run() error { 83 return nil 84 } 85 86 func (c *BaseClient) Close() error { 87 return c.cli.Close() 88 }