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.
 
 

47 lines
1.5 KiB

package generic
import (
"context"
"fmt"
"google.golang.org/grpc"
"sonet/pkg/utils/collect"
)
type GrpcGenericClientFactory struct {
scheme string
defaultOpts []grpc.DialOption
clientCache *collect.ConcurrentMap[string, *GrpcGenericClient]
}
func NewGpcGenericClientFactory(scheme string, defaultOpts ...grpc.DialOption) *GrpcGenericClientFactory {
return &GrpcGenericClientFactory{
scheme: scheme,
defaultOpts: defaultOpts,
}
}
func (f *GrpcGenericClientFactory) Init() {
// f.clientCache = &sync.Map{}
f.clientCache = collect.NewConcurrentMap[string, *GrpcGenericClient](8, func(serviceName string) string { return serviceName })
}
func (f *GrpcGenericClientFactory) NewClient(ctx context.Context, serviceName string, opts ...grpc.DialOption) (client *GrpcGenericClient, err error) {
addr := fmt.Sprintf("%s:///%s", f.scheme, serviceName)
dialOpts := make([]grpc.DialOption, 0, len(f.defaultOpts)+len(opts))
dialOpts = append(dialOpts, f.defaultOpts...)
dialOpts = append(dialOpts, opts...)
conn, err := grpc.DialContext(ctx, addr, dialOpts...)
if err != nil {
return
}
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) {
client, err, _ = f.clientCache.ComputeIfAbsentE(serviceName, func(serviceName string) (*GrpcGenericClient, error) {
return f.NewClient(ctx, serviceName, opts...)
})
return
}