Prechádzať zdrojové kódy

fix: 将连接缓存下来,如果需要清理自己处理

dcsunny 1 rok pred
rodič
commit
369dfd40d5
1 zmenil súbory, kde vykonal 28 pridanie a 4 odobranie
  1. 28 4
      grpc/client.go

+ 28 - 4
grpc/client.go

@@ -2,6 +2,7 @@ package grpc
 
 import (
 	"context"
+	"sync"
 	"time"
 
 	"git.ikuban.com/server/kratos-nacos/registry"
@@ -13,6 +14,11 @@ import (
 	grpc2 "google.golang.org/grpc"
 )
 
+var (
+	ConnMap  map[string]*grpc2.ClientConn
+	ConnLock sync.Mutex
+)
+
 type DialOption struct {
 	Middlewares []middleware.Middleware
 	Timeout     time.Duration
@@ -29,8 +35,14 @@ func GetDialInsecure(
 	if r == nil {
 		return nil, nil
 	}
-
-	conn, err := grpc.DialInsecure(context.Background(),
+	ConnLock.Lock()
+	conn, ok := ConnMap[clientName]
+	ConnLock.Unlock()
+	if ok {
+		return conn, nil
+	}
+	var err error
+	conn, err = grpc.DialInsecure(context.Background(),
 		endpoint,
 		grpc.WithDiscovery(r),
 		grpc.WithMiddleware(option.Middlewares...),
@@ -40,13 +52,22 @@ func GetDialInsecure(
 	if err != nil {
 		return nil, err
 	}
+	ConnLock.Lock()
+	ConnMap[clientName] = conn
+	ConnLock.Unlock()
 	return conn, nil
 }
 
 func GetDialSimple(clientName string, endpoint string, option *DialOption) (*grpc2.ClientConn, error) {
 	option = checkOption(option)
-
-	conn, err := grpc.DialInsecure(context.Background(),
+	ConnLock.Lock()
+	conn, ok := ConnMap[clientName]
+	ConnLock.Unlock()
+	if ok {
+		return conn, nil
+	}
+	var err error
+	conn, err = grpc.DialInsecure(context.Background(),
 		grpc.WithEndpoint(endpoint),
 		grpc.WithMiddleware(option.Middlewares...),
 		grpc.WithTimeout(option.Timeout),
@@ -55,6 +76,9 @@ func GetDialSimple(clientName string, endpoint string, option *DialOption) (*grp
 	if err != nil {
 		return nil, err
 	}
+	ConnLock.Lock()
+	ConnMap[clientName] = conn
+	ConnLock.Unlock()
 	return conn, nil
 }