client.go 1.9 KB

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