setup.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. "cp-system-management/parser"
  6. fmt "fmt"
  7. "time"
  8. grpc "google.golang.org/grpc"
  9. "google.golang.org/grpc/keepalive"
  10. )
  11. // 客户端集合
  12. var Device DeviceClient
  13. var Organization OrganizationClient
  14. func setupDeviceClient(kacp keepalive.ClientParameters, conns []*grpc.ClientConn) {
  15. // 根据是否为k8s来组装targets
  16. var serviceName string
  17. if parser.Conf.K8s {
  18. serviceName = parser.Conf.Rpc.Device.ServiceName
  19. } else {
  20. serviceName = parser.Conf.Rpc.Device.ServiceIp
  21. }
  22. // 发起一个连接并记录连接conn,后期释放
  23. if conn, err := grpc.Dial(fmt.Sprintf("%s:%d", serviceName,
  24. parser.Conf.Rpc.Device.ServicePort),
  25. grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp)); err == nil {
  26. Device = NewDeviceClient(conn)
  27. conns = append(conns, conn)
  28. } else {
  29. fmt.Println("[rpc] dial device conn err", err)
  30. }
  31. return
  32. }
  33. func setupOrganizationClient(kacp keepalive.ClientParameters, conns []*grpc.ClientConn) {
  34. // 根据是否为k8s来组装targets
  35. var serviceName string
  36. if parser.Conf.K8s {
  37. serviceName = parser.Conf.Rpc.Organization.ServiceName
  38. } else {
  39. serviceName = parser.Conf.Rpc.Organization.ServiceIp
  40. }
  41. // 发起一个连接并记录连接conn,后期释放
  42. if conn, err := grpc.Dial(fmt.Sprintf("%s:%d", serviceName,
  43. parser.Conf.Rpc.Organization.ServicePort),
  44. grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp)); err == nil {
  45. Organization = NewOrganizationClient(conn)
  46. conns = append(conns, conn)
  47. } else {
  48. fmt.Println("[rpc] dial organization conn err", err)
  49. }
  50. return
  51. }
  52. // SetupClients 创建客户端
  53. func SetupClients() (conns []*grpc.ClientConn) {
  54. // 客户端配置参数
  55. var kacp = keepalive.ClientParameters{
  56. // send pings every n seconds if there is no activity
  57. Time: time.Duration(parser.Conf.Rpc.Keepalive.ClientTime) * time.Second,
  58. // wait n second for ping ack before considering the connection dead
  59. Timeout: time.Duration(parser.Conf.Rpc.Keepalive.ClientTimeout) * time.Second,
  60. // send pings even without active streams
  61. PermitWithoutStream: true,
  62. }
  63. setupDeviceClient(kacp, conns)
  64. setupOrganizationClient(kacp, conns)
  65. return
  66. }