setup.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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-vehicle-style/etcd"
  6. "adm-vehicle-style/parser"
  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 Data DataClient
  15. func setupDataClient(kacp keepalive.ClientParameters, conns []*grpc.ClientConn) {
  16. // 根据是否为k8s来组装targets
  17. serviceName := parser.Conf.Rpc.ADMData.ServiceName
  18. builder, err := resolver.NewBuilder(etcd.Get())
  19. if err != nil {
  20. panic(err)
  21. }
  22. // 发起一个连接并记录连接conn,后期释放
  23. if conn, err := grpc.Dial("etcd:///"+parser.Conf.Rpc.Prefix+"/"+serviceName,
  24. grpc.WithResolvers(builder),
  25. grpc.WithBalancerName("round_robin"),
  26. grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp)); err == nil {
  27. Data = NewDataClient(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. kacp := keepalive.ClientParameters{
  38. // send pings every n seconds if there is no activity
  39. Time: time.Duration(parser.Conf.Rpc.Keepalive.ClientTime) * time.Second,
  40. // wait n second for ping ack before considering the connection dead
  41. Timeout: time.Duration(parser.Conf.Rpc.Keepalive.ClientTimeout) * time.Second,
  42. // send pings even without active streams
  43. PermitWithoutStream: true,
  44. }
  45. setupDataClient(kacp, conns)
  46. return
  47. }