setup.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2019 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package pb
  4. import (
  5. "lift-monitor/parser"
  6. "fmt"
  7. "time"
  8. grpc "google.golang.org/grpc"
  9. "google.golang.org/grpc/keepalive"
  10. )
  11. // 客户端集合
  12. var SmartAlarm SmartAlarmClient
  13. var SmartAuth SmartAuthClient
  14. func setupSmartAlarmClient(kacp keepalive.ClientParameters, conns []*grpc.ClientConn) {
  15. // 根据是否为k8s来组装targets
  16. var serviceName string
  17. if parser.Conf.K8s {
  18. serviceName = parser.Conf.Rpc.SmartAlarm.ServiceName
  19. } else {
  20. serviceName = parser.Conf.Rpc.SmartAlarm.ServiceIp
  21. }
  22. // 发起一个连接并记录连接conn,后期释放
  23. if conn, err := grpc.Dial(fmt.Sprintf("%s:%d", serviceName,
  24. parser.Conf.Rpc.SmartAlarm.ServicePort),
  25. grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp)); err == nil {
  26. SmartAlarm = NewSmartAlarmClient(conn)
  27. conns = append(conns, conn)
  28. } else {
  29. fmt.Println("[rpc] dial cabinet conn err", err)
  30. }
  31. return
  32. }
  33. func setupSmartAuthClient(kacp keepalive.ClientParameters, conns []*grpc.ClientConn) {
  34. // 根据是否为k8s来组装targets
  35. var serviceName string
  36. if parser.Conf.K8s {
  37. serviceName = parser.Conf.Rpc.SmartAuth.ServiceName
  38. } else {
  39. serviceName = parser.Conf.Rpc.SmartAuth.ServiceIp
  40. }
  41. // 发起一个连接并记录连接conn,后期释放
  42. if conn, err := grpc.Dial(fmt.Sprintf("%s:%d", serviceName,
  43. parser.Conf.Rpc.SmartAuth.ServicePort),
  44. grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp)); err == nil {
  45. SmartAuth = NewSmartAuthClient(conn)
  46. conns = append(conns, conn)
  47. } else {
  48. fmt.Println("[rpc] dial cabinet 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. setupSmartAlarmClient(kacp, conns)
  64. setupSmartAuthClient(kacp, conns)
  65. return
  66. }