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