client.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package rpcx
  2. import (
  3. "log"
  4. "time"
  5. "zero/core/discov"
  6. "zero/core/rpc"
  7. "zero/rpcx/auth"
  8. "google.golang.org/grpc"
  9. )
  10. type RpcClient struct {
  11. client rpc.Client
  12. }
  13. func MustNewClient(c RpcClientConf, options ...rpc.ClientOption) *RpcClient {
  14. cli, err := NewClient(c, options...)
  15. if err != nil {
  16. log.Fatal(err)
  17. }
  18. return cli
  19. }
  20. func NewClient(c RpcClientConf, options ...rpc.ClientOption) (*RpcClient, error) {
  21. var opts []rpc.ClientOption
  22. if c.HasCredential() {
  23. opts = append(opts, rpc.WithDialOption(grpc.WithPerRPCCredentials(&auth.Credential{
  24. App: c.App,
  25. Token: c.Token,
  26. })))
  27. }
  28. if c.Timeout > 0 {
  29. opts = append(opts, rpc.WithTimeout(time.Duration(c.Timeout)*time.Millisecond))
  30. }
  31. opts = append(opts, options...)
  32. var client rpc.Client
  33. var err error
  34. if len(c.Server) > 0 {
  35. client, err = rpc.NewDirectClient(c.Server, opts...)
  36. } else if err = c.Etcd.Validate(); err == nil {
  37. client, err = rpc.NewRoundRobinRpcClient(c.Etcd.Hosts, c.Etcd.Key, opts...)
  38. }
  39. if err != nil {
  40. return nil, err
  41. }
  42. return &RpcClient{
  43. client: client,
  44. }, nil
  45. }
  46. func NewClientNoAuth(c discov.EtcdConf) (*RpcClient, error) {
  47. client, err := rpc.NewRoundRobinRpcClient(c.Hosts, c.Key)
  48. if err != nil {
  49. return nil, err
  50. }
  51. return &RpcClient{
  52. client: client,
  53. }, nil
  54. }
  55. func (rc *RpcClient) Next() (*grpc.ClientConn, bool) {
  56. return rc.client.Next()
  57. }