From 83df1be84d9c37291989889ac0fbc3f21c231b4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E7=A5=A5=E8=B6=85?= Date: Wed, 30 Sep 2020 17:46:49 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E8=AF=81=E4=B9=A6=E7=AE=A1?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/rpc/rpc_client.go | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/internal/rpc/rpc_client.go b/internal/rpc/rpc_client.go index 375fb16..df7a838 100644 --- a/internal/rpc/rpc_client.go +++ b/internal/rpc/rpc_client.go @@ -17,8 +17,8 @@ import ( ) type RPCClient struct { - apiConfig *configs.APIConfig - nodeClients []pb.NodeServiceClient + apiConfig *configs.APIConfig + conns []*grpc.ClientConn } func NewRPCClient(apiConfig *configs.APIConfig) (*RPCClient, error) { @@ -26,8 +26,6 @@ func NewRPCClient(apiConfig *configs.APIConfig) (*RPCClient, error) { return nil, errors.New("api config should not be nil") } - nodeClients := []pb.NodeServiceClient{} - conns := []*grpc.ClientConn{} for _, endpoint := range apiConfig.RPC.Endpoints { conn, err := grpc.Dial(endpoint, grpc.WithInsecure()) @@ -40,22 +38,14 @@ func NewRPCClient(apiConfig *configs.APIConfig) (*RPCClient, error) { return nil, errors.New("[RPC]no available endpoints") } - // node clients - for _, conn := range conns { - nodeClients = append(nodeClients, pb.NewNodeServiceClient(conn)) - } - return &RPCClient{ - apiConfig: apiConfig, - nodeClients: nodeClients, + apiConfig: apiConfig, + conns: conns, }, nil } func (this *RPCClient) NodeRPC() pb.NodeServiceClient { - if len(this.nodeClients) > 0 { - return this.nodeClients[rands.Int(0, len(this.nodeClients)-1)] - } - return nil + return pb.NewNodeServiceClient(this.pickConn()) } func (this *RPCClient) Context() context.Context { @@ -79,3 +69,11 @@ func (this *RPCClient) Context() context.Context { ctx = metadata.AppendToOutgoingContext(ctx, "nodeId", this.apiConfig.NodeId, "token", token) return ctx } + +// 随机选择一个连接 +func (this *RPCClient) pickConn() *grpc.ClientConn { + if len(this.conns) == 0 { + return nil + } + return this.conns[rands.Int(0, len(this.conns)-1)] +}