2 Star 1 Fork 1

mosache/YFrame

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
client.go 1.47 KB
一键复制 编辑 原始数据 按行查看 历史
ヤ沒脩袮兲︶ 提交于 2023-09-05 18:29 . temp
package micro
import (
"context"
"fmt"
"gitee.com/mosache/YFrame/micro/registry"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"time"
)
type Client struct {
r registry.Registry
insecure bool
balancer string // lb name
}
type ClientOption func(c *Client)
func ClientWithInsecure(insecure bool) ClientOption {
return func(c *Client) {
c.insecure = insecure
}
}
func ClientWithRegistry(r registry.Registry) ClientOption {
return func(c *Client) {
c.r = r
}
}
func ClientWithBalancer(balancer string) ClientOption {
return func(c *Client) {
c.balancer = balancer
}
}
func NewClient(opts ...ClientOption) (*Client, error) {
c := &Client{insecure: false}
for _, opt := range opts {
opt(c)
}
return c, nil
}
func (c *Client) Dial(ctx context.Context, serviceName string) (*grpc.ClientConn, error) {
dialOpts := make([]grpc.DialOption, 0)
if c.r != nil {
builder := NewRegisterBuilder(c.r, GrpcResolverBuilderWithTimeOut(time.Second*3))
dialOpts = append(dialOpts, grpc.WithResolvers(builder))
}
if c.insecure {
dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
/// 用了lb
if len(c.balancer) > 0 {
dialOpts = append(dialOpts, grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy":"%s"}`, c.balancer)))
}
grpcClient, err := grpc.DialContext(ctx, fmt.Sprintf("discovery:///%s", serviceName),
dialOpts...)
if err != nil {
return nil, err
}
return grpcClient, err
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/mosache/YFrame.git
git@gitee.com:mosache/YFrame.git
mosache
YFrame
YFrame
v0.1.53

搜索帮助