setup.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2019 autocareai.com. All rights reserved.
  2. // Use of this source code is governed by autocareai.com.
  3. package pb
  4. import (
  5. "gadm-ods/common.in/clinit"
  6. "gadm-ods/common.in/config"
  7. fmt "fmt"
  8. "time"
  9. "go.etcd.io/etcd/client/v3/naming/resolver"
  10. grpc "google.golang.org/grpc"
  11. "google.golang.org/grpc/keepalive"
  12. )
  13. // 客户端集合
  14. var AdmTask AdmTaskClient
  15. func setupAdmTaskClient(kacp keepalive.ClientParameters, conns []*grpc.ClientConn) {
  16. // 根据是否为k8s来组装targets
  17. serviceName := config.Conf.Rpc.AdmTask.ServiceName
  18. builder, err := resolver.NewBuilder(clinit.GetEtcdClient())
  19. if err != nil {
  20. panic(err)
  21. }
  22. // 发起一个连接并记录连接conn,后期释放
  23. if conn, err := grpc.Dial("etcd:///"+config.Conf.Rpc.Prefix+"/"+serviceName,
  24. grpc.WithResolvers(builder),
  25. grpc.WithBalancerName("round_robin"),
  26. grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp)); err == nil {
  27. AdmTask = NewAdmTaskClient(conn)
  28. conns = append(conns, conn)
  29. } else {
  30. fmt.Println("[rpc] dial cabinet conn err", err)
  31. }
  32. return
  33. }
  34. func setupAdmTaskK8sClient(kacp keepalive.ClientParameters, conns []*grpc.ClientConn) {
  35. // 发起一个连接并记录连接conn,后期释放
  36. if conn, err := grpc.Dial(fmt.Sprintf("%s:%s", config.Conf.Rpc.AdmTask.ServiceIp,
  37. config.Conf.Rpc.AdmTask.ServicePort),
  38. grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp)); err == nil {
  39. AdmTask = NewAdmTaskClient(conn)
  40. conns = append(conns, conn)
  41. } else {
  42. fmt.Println("[rpc] dial cabinet conn err", err)
  43. }
  44. return
  45. }
  46. // SetupClients 创建客户端
  47. func SetupClients(discoverType string) (conns []*grpc.ClientConn) {
  48. // 客户端配置参数
  49. clientTime, _ := config.Conf.Rpc.Keepalive.ClientTime.Int64()
  50. clientTimeout, _ := config.Conf.Rpc.Keepalive.ClientTimeout.Int64()
  51. kacp := keepalive.ClientParameters{
  52. // send pings every n seconds if there is no activity
  53. Time: time.Duration(clientTime) * time.Second,
  54. // wait n second for ping ack before considering the connection dead
  55. Timeout: time.Duration(clientTimeout) * time.Second,
  56. // send pings even without active streams
  57. PermitWithoutStream: true,
  58. }
  59. if discoverType == "etcd"{
  60. setupAdmTaskClient(kacp, conns)
  61. }else{
  62. setupAdmTaskK8sClient(kacp, conns)
  63. }
  64. return
  65. }