You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.7 KiB

6 years ago
6 years ago
6 years ago
  1. package util
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. "google.golang.org/grpc"
  7. "google.golang.org/grpc/keepalive"
  8. )
  9. var (
  10. // cache grpc connections
  11. grpcClients = make(map[string]*grpc.ClientConn)
  12. grpcClientsLock sync.Mutex
  13. )
  14. func NewGrpcServer() *grpc.Server {
  15. return grpc.NewServer(grpc.KeepaliveParams(keepalive.ServerParameters{
  16. Time: 10 * time.Second, // wait time before ping if no activity
  17. Timeout: 20 * time.Second, // ping timeout
  18. }), grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
  19. MinTime: 60 * time.Second, // min time a client should wait before sending a ping
  20. }))
  21. }
  22. func GrpcDial(address string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
  23. opts = append(opts, grpc.WithBlock())
  24. opts = append(opts, grpc.WithTimeout(time.Duration(5*time.Second)))
  25. opts = append(opts, grpc.WithInsecure())
  26. opts = append(opts, grpc.WithKeepaliveParams(keepalive.ClientParameters{
  27. Time: 30 * time.Second, // client ping server if no activity for this long
  28. Timeout: 20 * time.Second,
  29. }))
  30. return grpc.Dial(address, opts...)
  31. }
  32. func WithCachedGrpcClient(fn func(*grpc.ClientConn) error, address string, opts ...grpc.DialOption) error {
  33. grpcClientsLock.Lock()
  34. existingConnection, found := grpcClients[address]
  35. if found {
  36. grpcClientsLock.Unlock()
  37. return fn(existingConnection)
  38. }
  39. grpcConnection, err := GrpcDial(address, opts...)
  40. if err != nil {
  41. grpcClientsLock.Unlock()
  42. return fmt.Errorf("fail to dial %s: %v", address, err)
  43. }
  44. grpcClients[address] = grpcConnection
  45. grpcClientsLock.Unlock()
  46. err = fn(grpcConnection)
  47. if err != nil {
  48. grpcClientsLock.Lock()
  49. delete(grpcClients, address)
  50. grpcClientsLock.Unlock()
  51. }
  52. return err
  53. }