setup.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. "time"
  7. "adm-gateway/etcd"
  8. "adm-gateway/parser"
  9. "go.etcd.io/etcd/client/v3/naming/resolver"
  10. grpc "google.golang.org/grpc"
  11. "google.golang.org/grpc/keepalive"
  12. )
  13. // 客户端集合
  14. var VehicleStyle VehicleStyleClient
  15. var Management ManagementClient
  16. func setupVehicleStyleClient(kacp keepalive.ClientParameters, conns []*grpc.ClientConn) {
  17. // 根据是否为k8s来组装targets
  18. serviceName := parser.Conf.Rpc.ADMVehicleStyle.ServiceName
  19. builder, err := resolver.NewBuilder(etcd.Get())
  20. if err != nil {
  21. panic(err)
  22. }
  23. // 发起一个连接并记录连接conn,后期释放
  24. if conn, err := grpc.Dial("etcd:///"+parser.Conf.Rpc.Prefix+"/"+serviceName,
  25. grpc.WithResolvers(builder),
  26. grpc.WithBalancerName("round_robin"),
  27. grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp)); err == nil {
  28. VehicleStyle = NewVehicleStyleClient(conn)
  29. conns = append(conns, conn)
  30. } else {
  31. fmt.Println("[rpc] dial cabinet conn err", err)
  32. }
  33. return
  34. }
  35. func setupManagementClient(kacp keepalive.ClientParameters, conns []*grpc.ClientConn) {
  36. // 根据是否为k8s来组装targets
  37. serviceName := parser.Conf.Rpc.AdmManagement.ServiceName
  38. builder, err := resolver.NewBuilder(etcd.Get())
  39. if err != nil {
  40. panic(err)
  41. }
  42. // 发起一个连接并记录连接conn,后期释放
  43. if conn, err := grpc.Dial("etcd:///"+parser.Conf.Rpc.Prefix+"/"+serviceName,
  44. grpc.WithResolvers(builder),
  45. grpc.WithBalancerName("round_robin"),
  46. grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp)); err == nil {
  47. Management = NewManagementClient(conn)
  48. conns = append(conns, conn)
  49. } else {
  50. fmt.Println("[rpc] dial cabinet conn err", err)
  51. }
  52. return
  53. }
  54. // SetupClients 创建客户端
  55. func SetupClients() (conns []*grpc.ClientConn) {
  56. // 客户端配置参数
  57. kacp := keepalive.ClientParameters{
  58. // send pings every n seconds if there is no activity
  59. Time: time.Duration(parser.Conf.Rpc.Keepalive.ClientTime) * time.Second,
  60. // wait n second for ping ack before considering the connection dead
  61. Timeout: time.Duration(parser.Conf.Rpc.Keepalive.ClientTimeout) * time.Second,
  62. // send pings even without active streams
  63. PermitWithoutStream: true,
  64. }
  65. setupVehicleStyleClient(kacp, conns)
  66. setupManagementClient(kacp, conns)
  67. return
  68. }