setup.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package pb
  4. import (
  5. fmt "fmt"
  6. "property-management/parser"
  7. "time"
  8. "go.etcd.io/etcd/client/v3/naming/resolver"
  9. grpc "google.golang.org/grpc"
  10. "google.golang.org/grpc/keepalive"
  11. )
  12. // 客户端集合
  13. var Company CompanyClient
  14. func setupCompanyClient(kacp keepalive.ClientParameters, conns []*grpc.ClientConn) {
  15. // 根据是否为k8s来组装targets
  16. var serviceName string
  17. if parser.Conf.K8s {
  18. serviceName = parser.Conf.Rpc.Company.ServiceName
  19. } else {
  20. serviceName = parser.Conf.Rpc.Company.ServiceIp
  21. }
  22. // 发起一个连接并记录连接conn,后期释放
  23. if conn, err := grpc.Dial(fmt.Sprintf("%s:%d", serviceName,
  24. parser.Conf.Rpc.Company.ServicePort),
  25. grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp)); err == nil {
  26. Company = NewCompanyClient(conn)
  27. conns = append(conns, conn)
  28. } else {
  29. fmt.Println("[rpc] dial company conn err", err)
  30. }
  31. return
  32. }
  33. func setupCompanyClient2(kacp keepalive.ClientParameters, conns []*grpc.ClientConn) {
  34. // 根据是否为k8s来组装targets
  35. var serviceName string
  36. serviceName = parser.Conf.Rpc.Company.ServiceName
  37. builder, err := resolver.NewBuilder(parser.GetEtcdClient())
  38. if err != nil {
  39. panic(err)
  40. }
  41. // 发起一个连接并记录连接conn,后期释放
  42. if conn, err := grpc.Dial("etcd:///"+parser.Conf.Rpc.Prefix+"/"+serviceName,
  43. grpc.WithResolvers(builder),
  44. grpc.WithBalancerName("round_robin"),
  45. grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp)); err == nil {
  46. Company = NewCompanyClient(conn)
  47. conns = append(conns, conn)
  48. } else {
  49. fmt.Println("[rpc] dial company conn err", err)
  50. }
  51. return
  52. }
  53. // SetupClients 创建客户端
  54. func SetupClients() (conns []*grpc.ClientConn) {
  55. // 客户端配置参数
  56. var kacp = keepalive.ClientParameters{
  57. // send pings every n seconds if there is no activity
  58. Time: time.Duration(parser.Conf.Rpc.Keepalive.ClientTime) * time.Second,
  59. // wait n second for ping ack before considering the connection dead
  60. Timeout: time.Duration(parser.Conf.Rpc.Keepalive.ClientTimeout) * time.Second,
  61. // send pings even without active streams
  62. PermitWithoutStream: true,
  63. }
  64. if len(parser.Conf.EtcdAddrs) == 0 {
  65. setupCompanyClient(kacp, conns)
  66. return
  67. }
  68. setupCompanyClient2(kacp, conns)
  69. return
  70. }