setup.go 2.0 KB

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