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.
49 lines
1.5 KiB
49 lines
1.5 KiB
package generic |
|
|
|
import ( |
|
"context" |
|
"fmt" |
|
"sig-pub/pkg/utils/collect" |
|
|
|
"google.golang.org/grpc" |
|
) |
|
|
|
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() (err error) { |
|
f.clientCache = collect.NewConcurrentMap[string, *GrpcGenericClient](8, func(serviceName string) string { return serviceName }) |
|
return |
|
} |
|
|
|
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.NewClient(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) { |
|
// todo 优化 |
|
client, err, _ = f.clientCache.ComputeIfAbsentE(serviceName, func(serviceName string) (*GrpcGenericClient, error) { |
|
return f.NewClient(ctx, serviceName, opts...) |
|
}) |
|
return |
|
}
|
|
|