setup.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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-supplier-management/parser"
  8. "google.golang.org/grpc"
  9. "google.golang.org/grpc/keepalive"
  10. )
  11. // 客户端集合
  12. var Thirdparty SmartSiteThirdpartyClient
  13. var Provincial SmartProvincialClient
  14. func setupSmartSiteThirdpartyClient(kacp keepalive.ClientParameters, conns []*grpc.ClientConn) {
  15. // 根据是否为k8s来组装targets
  16. var serviceName string
  17. if parser.Conf.K8s {
  18. serviceName = parser.Conf.Rpc.SmartThirdparty.ServiceName
  19. } else {
  20. serviceName = parser.Conf.Rpc.SmartThirdparty.ServiceIp
  21. }
  22. // 发起一个连接并记录连接conn,后期释放
  23. if conn, err := grpc.Dial(fmt.Sprintf("%s:%d", serviceName,
  24. parser.Conf.Rpc.SmartThirdparty.ServicePort),
  25. grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp)); err == nil {
  26. Thirdparty = NewSmartSiteThirdpartyClient(conn)
  27. conns = append(conns, conn)
  28. } else {
  29. fmt.Println("[rpc] dial thirdparty conn err", err)
  30. }
  31. return
  32. }
  33. func setupSmartProvincialClient(kacp keepalive.ClientParameters, conns []*grpc.ClientConn) {
  34. // 根据是否为k8s来组装targets
  35. var serviceName string
  36. if parser.Conf.K8s {
  37. serviceName = parser.Conf.Rpc.SmartProvincial.ServiceName
  38. } else {
  39. serviceName = parser.Conf.Rpc.SmartProvincial.ServiceIp
  40. }
  41. // 发起一个连接并记录连接conn,后期释放
  42. if conn, err := grpc.Dial(fmt.Sprintf("%s:%d", serviceName,
  43. parser.Conf.Rpc.SmartProvincial.ServicePort),
  44. grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp)); err == nil {
  45. Provincial = NewSmartProvincialClient(conn)
  46. conns = append(conns, conn)
  47. } else {
  48. fmt.Println("[rpc] dial provincial 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. setupSmartSiteThirdpartyClient(kacp, conns)
  64. setupSmartProvincialClient(kacp, conns)
  65. return
  66. }