32 Star 181 Fork 430

极客时间/极客时间-Go实战训练营

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
client.go 1.69 KB
一键复制 编辑 原始数据 按行查看 历史
Ming Deng 提交于 2022-12-04 14:06 . demo 12.3
package demo
import (
"fmt"
"gitee.com/geektime-geekbang/geektime-go/demo/registry"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/balancer"
"google.golang.org/grpc/balancer/base"
"google.golang.org/grpc/resolver"
"time"
)
type ClientOption func(client *Client)
type Client struct {
rb resolver.Builder
insecure bool
balancer balancer.Builder
}
func NewClient(opts ...ClientOption) *Client {
client := &Client{}
for _, opt := range opts {
opt(client)
}
return client
}
func (c *Client) Dial(ctx context.Context, service string) (*grpc.ClientConn, error) {
opts := []grpc.DialOption{grpc.WithResolvers(c.rb)}
address := fmt.Sprintf("registry:///%s", service)
if c.insecure {
opts = append(opts, grpc.WithInsecure())
}
if c.balancer != nil {
opts = append(opts, grpc.WithDefaultServiceConfig(
fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`,
c.balancer.Name())))
}
return grpc.DialContext(ctx, address, opts...)
}
func ClientWithRegistry(r registry.Registry, timeout time.Duration) ClientOption {
return func(client *Client) {
client.rb = NewResolverBuilder(r, timeout)
}
}
func ClientWithInsecure() ClientOption {
return func(client *Client) {
client.insecure = true
}
}
func ClientWithPickerBuilder(name string, b base.PickerBuilder) ClientOption {
return func(client *Client) {
builder := base.NewBalancerBuilder(name, b, base.Config{HealthCheck: true})
balancer.Register(builder)
client.balancer = builder
}
}
// 伪代码
// func (c *Client) DialPsu(ctx context.Context, service string) (*grpc.ClientConn, error) {
// resolver := c.rb
//
// grpc.DialContext(ctx,
// "registry:///user-service",
// grpc.WithResolvers(resolver))
// }
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/geektime-geekbang/geektime-go.git
git@gitee.com:geektime-geekbang/geektime-go.git
geektime-geekbang
geektime-go
极客时间-Go实战训练营
master

搜索帮助