client.go 1.9 KB

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