client.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package lancergateway
  2. import (
  3. "time"
  4. "errors"
  5. "fmt"
  6. "go-common/library/net/rpc/warden/resolver"
  7. "go-common/library/net/rpc/warden/balancer/wrr"
  8. "go-common/library/naming/discovery"
  9. xtime "go-common/library/time"
  10. "google.golang.org/grpc"
  11. )
  12. type Config struct {
  13. AppId string `toml:"appId"`
  14. Timeout xtime.Duration `toml:"timeout"`
  15. Subset int `toml:"subset"`
  16. }
  17. func (c *Config) ConfigValidate() (error) {
  18. if c == nil {
  19. return errors.New("config of LancerGateway can't be nil")
  20. }
  21. if c.AppId == "" {
  22. c.AppId = "datacenter.lancer.gateway2-server"
  23. }
  24. if c.Timeout == 0 {
  25. c.Timeout = xtime.Duration(time.Second * 5)
  26. }
  27. if c.Subset == 0 {
  28. c.Subset = 5
  29. }
  30. return nil
  31. }
  32. func init() {
  33. resolver.Register(discovery.Builder())
  34. }
  35. // NewClient new member grpc client
  36. func NewClient(c *Config) (Gateway2ServerClient, error) {
  37. opts := []grpc.DialOption{
  38. grpc.WithInsecure(),
  39. grpc.WithBalancerName(wrr.Name),
  40. }
  41. if c.Timeout != 0 {
  42. opts = append(opts, grpc.WithTimeout(time.Duration(c.Timeout)))
  43. }
  44. conn, err := grpc.Dial(fmt.Sprintf("discovery://default/%s?subset=%d", c.AppId, c.Subset), opts...)
  45. if err != nil {
  46. return nil, err
  47. }
  48. return NewGateway2ServerClient(conn), nil
  49. }