setup.go 1.5 KB

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