setup.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package pb
  4. import (
  5. "adm-dws/common.in/clinit"
  6. "adm-dws/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. // SetupClients 创建客户端
  35. func SetupClients() (conns []*grpc.ClientConn) {
  36. // 客户端配置参数
  37. clientTime, _ := config.Conf.Rpc.Keepalive.ClientTime.Int64()
  38. clientTimeout, _ := config.Conf.Rpc.Keepalive.ClientTimeout.Int64()
  39. kacp := keepalive.ClientParameters{
  40. // send pings every n seconds if there is no activity
  41. Time: time.Duration(clientTime) * time.Second,
  42. // wait n second for ping ack before considering the connection dead
  43. Timeout: time.Duration(clientTimeout) * time.Second,
  44. // send pings even without active streams
  45. PermitWithoutStream: true,
  46. }
  47. setupAdmTaskClient(kacp, conns)
  48. return
  49. }