client.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. WithUnaryClientInterceptor = internal.WithUnaryClientInterceptor
  14. )
  15. type (
  16. ClientOption = internal.ClientOption
  17. Client interface {
  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, opts ...ClientOption) (Client, error) {
  58. client, err := internal.NewClient(internal.BuildDiscovTarget(c.Hosts, c.Key), opts...)
  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) Conn() *grpc.ClientConn {
  70. return rc.client.Conn()
  71. }