You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.4 KiB
51 lines
1.4 KiB
package generic |
|
|
|
import ( |
|
"context" |
|
"fmt" |
|
"google.golang.org/grpc" |
|
"sonet/pkg/grpc/discovery" |
|
"sync" |
|
) |
|
|
|
type GrpcGenericClientFactory struct { |
|
resolver *discovery.Resolver |
|
defaultOpts []grpc.DialOption |
|
clientCache *sync.Map |
|
} |
|
|
|
func NewGpcGenericClientFactory(resolver *discovery.Resolver, defaultOpts ...grpc.DialOption) *GrpcGenericClientFactory { |
|
return &GrpcGenericClientFactory{ |
|
resolver: resolver, |
|
defaultOpts: defaultOpts, |
|
} |
|
} |
|
|
|
func (f *GrpcGenericClientFactory) Init() { |
|
f.clientCache = &sync.Map{} |
|
} |
|
|
|
func (f *GrpcGenericClientFactory) NewClient(ctx context.Context, serviceName string, opts ...grpc.DialOption) (client *GrpcGenericClient, err error) { |
|
addr := fmt.Sprintf("%s:///%s", f.resolver.Scheme(), serviceName) |
|
dialOpts := make([]grpc.DialOption, len(f.defaultOpts)+len(opts)) |
|
dialOpts = append(dialOpts, f.defaultOpts...) |
|
dialOpts = append(dialOpts, opts...) |
|
conn, err := grpc.DialContext(ctx, addr, dialOpts...) |
|
client = NewGpcGenericClient(serviceName, conn) |
|
err = client.Init(ctx) |
|
return |
|
} |
|
|
|
func (f *GrpcGenericClientFactory) GetClient(ctx context.Context, serviceName string, opts ...grpc.DialOption) (client *GrpcGenericClient, err error) { |
|
val, ok := f.clientCache.Load(serviceName) |
|
if ok { |
|
client = val.(*GrpcGenericClient) |
|
return |
|
} |
|
client, err = f.NewClient(ctx, serviceName, opts...) |
|
if err != nil { |
|
return |
|
} |
|
f.clientCache.Store(serviceName, client) |
|
return |
|
}
|
|
|