client.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package zrpc
  2. import (
  3. "log"
  4. "time"
  5. "github.com/tal-tech/go-zero/zrpc/internal"
  6. "github.com/tal-tech/go-zero/zrpc/internal/auth"
  7. "google.golang.org/grpc"
  8. )
  9. var (
  10. // WithDialOption is an alias of internal.WithDialOption.
  11. WithDialOption = internal.WithDialOption
  12. // WithTimeout is an alias of internal.WithTimeout.
  13. WithTimeout = internal.WithTimeout
  14. // WithRetry is an alias of internal.WithRetry.
  15. WithRetry = internal.WithRetry
  16. // WithUnaryClientInterceptor is an alias of internal.WithUnaryClientInterceptor.
  17. WithUnaryClientInterceptor = internal.WithUnaryClientInterceptor
  18. )
  19. type (
  20. // Client is an alias of internal.Client.
  21. Client = internal.Client
  22. // ClientOption is an alias of internal.ClientOption.
  23. ClientOption = internal.ClientOption
  24. // A RpcClient is a rpc client.
  25. RpcClient struct {
  26. client Client
  27. }
  28. )
  29. // MustNewClient returns a Client, exits on any error.
  30. func MustNewClient(c RpcClientConf, options ...ClientOption) Client {
  31. cli, err := NewClient(c, options...)
  32. if err != nil {
  33. log.Fatal(err)
  34. }
  35. return cli
  36. }
  37. // NewClient returns a Client.
  38. func NewClient(c RpcClientConf, options ...ClientOption) (Client, error) {
  39. var opts []ClientOption
  40. if c.HasCredential() {
  41. opts = append(opts, WithDialOption(grpc.WithPerRPCCredentials(&auth.Credential{
  42. App: c.App,
  43. Token: c.Token,
  44. })))
  45. }
  46. if c.Timeout > 0 {
  47. opts = append(opts, WithTimeout(time.Duration(c.Timeout)*time.Millisecond))
  48. }
  49. if c.Retry {
  50. opts = append(opts, WithRetry())
  51. }
  52. opts = append(opts, options...)
  53. var target string
  54. var err error
  55. if len(c.Endpoints) > 0 {
  56. target = internal.BuildDirectTarget(c.Endpoints)
  57. } else if len(c.Target) > 0 {
  58. target = c.Target
  59. } else {
  60. if err = c.Etcd.Validate(); err != nil {
  61. return nil, err
  62. }
  63. target = internal.BuildDiscovTarget(c.Etcd.Hosts, c.Etcd.Key)
  64. }
  65. client, err := internal.NewClient(target, opts...)
  66. if err != nil {
  67. return nil, err
  68. }
  69. return &RpcClient{
  70. client: client,
  71. }, nil
  72. }
  73. // NewClientWithTarget returns a Client with connecting to given target.
  74. func NewClientWithTarget(target string, opts ...ClientOption) (Client, error) {
  75. return internal.NewClient(target, opts...)
  76. }
  77. // Conn returns the underlying grpc.ClientConn.
  78. func (rc *RpcClient) Conn() *grpc.ClientConn {
  79. return rc.client.Conn()
  80. }