client.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. Client interface {
  16. Conn() *grpc.ClientConn
  17. }
  18. RpcClient struct {
  19. client Client
  20. }
  21. )
  22. func MustNewClient(c RpcClientConf, options ...internal.ClientOption) Client {
  23. cli, err := NewClient(c, options...)
  24. if err != nil {
  25. log.Fatal(err)
  26. }
  27. return cli
  28. }
  29. func NewClient(c RpcClientConf, options ...internal.ClientOption) (Client, error) {
  30. var opts []internal.ClientOption
  31. if c.HasCredential() {
  32. opts = append(opts, WithDialOption(grpc.WithPerRPCCredentials(&auth.Credential{
  33. App: c.App,
  34. Token: c.Token,
  35. })))
  36. }
  37. if c.Timeout > 0 {
  38. opts = append(opts, WithTimeout(time.Duration(c.Timeout)*time.Millisecond))
  39. }
  40. opts = append(opts, options...)
  41. var client Client
  42. var err error
  43. if len(c.Endpoints) > 0 {
  44. client, err = internal.NewClient(internal.BuildDirectTarget(c.Endpoints), opts...)
  45. } else if err = c.Etcd.Validate(); err == nil {
  46. client, err = internal.NewClient(internal.BuildDiscovTarget(c.Etcd.Hosts, c.Etcd.Key), opts...)
  47. }
  48. if err != nil {
  49. return nil, err
  50. }
  51. return &RpcClient{
  52. client: client,
  53. }, nil
  54. }
  55. func NewClientNoAuth(c discov.EtcdConf) (Client, error) {
  56. client, err := internal.NewClient(internal.BuildDiscovTarget(c.Hosts, c.Key))
  57. if err != nil {
  58. return nil, err
  59. }
  60. return &RpcClient{
  61. client: client,
  62. }, nil
  63. }
  64. func NewClientWithTarget(target string, opts ...internal.ClientOption) (Client, error) {
  65. return internal.NewClient(target, opts...)
  66. }
  67. func (rc *RpcClient) Conn() *grpc.ClientConn {
  68. return rc.client.Conn()
  69. }