grpc connections use sync.Map

This commit is contained in:
yedf2 2021-08-17 10:03:36 +08:00
parent 57fa97e942
commit fa98442a7b
2 changed files with 10 additions and 10 deletions

View File

@ -4,6 +4,7 @@ import (
context "context" context "context"
"fmt" "fmt"
"strings" "strings"
sync "sync"
"github.com/yedf/dtm/dtmcli" "github.com/yedf/dtm/dtmcli"
grpc "google.golang.org/grpc" grpc "google.golang.org/grpc"
@ -12,20 +13,21 @@ import (
"google.golang.org/protobuf/types/known/emptypb" "google.golang.org/protobuf/types/known/emptypb"
) )
var clients = map[string]*grpc.ClientConn{} var clients sync.Map
// GetGrpcConn 1 // GetGrpcConn 1
func GetGrpcConn(grpcServer string) (conn *grpc.ClientConn, rerr error) { func GetGrpcConn(grpcServer string) (conn *grpc.ClientConn, rerr error) {
if clients[grpcServer] == nil { v, ok := clients.Load(grpcServer)
if !ok {
dtmcli.Logf("grpc client connecting %s", grpcServer) dtmcli.Logf("grpc client connecting %s", grpcServer)
conn, err := grpc.Dial(grpcServer, grpc.WithInsecure(), grpc.WithUnaryInterceptor(GrpcClientLog)) conn, rerr := grpc.Dial(grpcServer, grpc.WithInsecure(), grpc.WithUnaryInterceptor(GrpcClientLog))
if err == nil { if rerr == nil {
clients[grpcServer] = conn clients.Store(grpcServer, conn)
v = conn
dtmcli.Logf("grpc client inited for %s", grpcServer) dtmcli.Logf("grpc client inited for %s", grpcServer)
} }
} }
conn = clients[grpcServer] return v.(*grpc.ClientConn), rerr
return
} }
// MustGetGrpcConn 1 // MustGetGrpcConn 1

View File

@ -11,9 +11,7 @@ func init() {
gid := dtmgrpc.MustGenGid(DtmGrpcServer) gid := dtmgrpc.MustGenGid(DtmGrpcServer)
err := dtmgrpc.TccGlobalTransaction(DtmGrpcServer, gid, func(tcc *dtmgrpc.TccGrpc) error { err := dtmgrpc.TccGlobalTransaction(DtmGrpcServer, gid, func(tcc *dtmgrpc.TccGrpc) error {
data := dtmcli.MustMarshal(&TransReq{Amount: 30}) data := dtmcli.MustMarshal(&TransReq{Amount: 30})
r, err := tcc.CallBranch(data, BusiGrpc+"/examples.Busi/TransOutTcc", BusiGrpc+"/examples.Busi/TransOutConfirm", BusiGrpc+"/examples.Busi/TransOutRevert") _, err := tcc.CallBranch(data, BusiGrpc+"/examples.Busi/TransOutTcc", BusiGrpc+"/examples.Busi/TransOutConfirm", BusiGrpc+"/examples.Busi/TransOutRevert")
dtmcli.LogRedf("callbranch return %v", r)
dtmcli.LogRedf("callbranch return data %s", string(r.BusiData))
if err != nil { if err != nil {
return err return err
} }