客户端开发

不同的注册中心有不同的ClientSelector, rpcx利用ClientSelector配置到注册中心的连接以及客户端的连接,然后根据ClientSelector生成rpcx.Client。

注册中心那一章我们已经介绍了三种ClientSeletor,目前rpcx支持五种ClientSelector:

  1. type ConsulClientSelector
  2. func NewConsulClientSelector(consulAddress string, serviceName string, sessionTimeout time.Duration, sm rpcx.SelectMode, dailTimeout time.Duration) *ConsulClientSelector
  3. func NewEtcdClientSelector(etcdServers []string, basePath string, sessionTimeout time.Duration, sm rpcx.SelectMode, dailTimeout time.Duration) *EtcdClientSelector
  4. func NewMultiClientSelector(servers []*ServerPeer, sm rpcx.SelectMode, dailTimeout time.Duration) *MultiClientSelector
  5. func NewZooKeeperClientSelector(zkServers []string, basePath string, sessionTimeout time.Duration, sm rpcx.SelectMode, dailTimeout time.Duration) *ZooKeeperClientSelector
  6. type DirectClientSelector struct { Network, Address string DialTimeout time.Duration Client *Client }

它们都实现了ClientSelector接口。

  1. type ClientSelector interface {
  2. //Select returns a new client and it also update current client
  3. Select(clientCodecFunc ClientCodecFunc, options ...interface{}) (*rpc.Client, error)
  4. //SetClient set current client
  5. SetClient(*Client)
  6. SetSelectMode(SelectMode)
  7. //AllClients returns all Clients
  8. AllClients(clientCodecFunc ClientCodecFunc) []*rpc.Client }

Select从服务列表中根据路由算法选择一个服务来调用,它返回的是一个rpc.Client对象,这个对象建立了对实际选择的服务的连接。
SetClient用来建立对当前选择的Client的引用,它用来关联一个rpcx.Client。
SetSelectMode可以用来设置路由算法,路由算法根据一定的规则从服务列表中来选择服务。
AllClients返回对所有的服务的rpc.Client slice。

所以你可以看到,底层rpcx还是利用官方库net/rpc进行通讯的。因此通过NewClient得到的rpcx.Client调用方法和官方库类似,Call是同步调用,Go是异步调用,调用完毕后可以Close释放连接。
Auth方法可以设置授权验证的信息。

  1. type Client
  2. func NewClient(s ClientSelector) *Client
  3. func (c *Client) Auth(authorization, tag string) error
  4. func (c *Client) Call(serviceMethod string, args interface{}, reply interface{}) (err error)
  5. func (c *Client) Close() error
  6. func (c *Client) Go(serviceMethod string, args interface{}, reply interface{}, done chan *rpc.Call) *rpc.Call

rpcx.Client的定义如下:

  1. type Client struct {
  2. ClientSelector ClientSelector
  3. ClientCodecFunc ClientCodecFunc
  4. PluginContainer IClientPluginContainer
  5. FailMode FailMode
  6. TLSConfig *tls.Config
  7. Retries int
  8. //Timeout sets deadline for underlying net.Conns
  9. Timeout time.Duration
  10. //Timeout sets readdeadline for underlying net.Conns
  11. ReadTimeout time.Duration
  12. //Timeout sets writedeadline for underlying net.Conns
  13. WriteTimeout time.Duration
  14. // contains filtered or unexported fields
  15. }

你可以设置rpcx.Client的序列化方式、TLS、失败模式、失败重试次数,超时等,还可以往它的插件容器中增加插件。

重试次数只在失败模式Failover或者Failtry下起作用。