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.

65 lines
1.6 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.WithInsecure())
  24. opts = append(opts, grpc.WithKeepaliveParams(keepalive.ClientParameters{
  25. Time: 30 * time.Second, // client ping server if no activity for this long
  26. Timeout: 20 * time.Second,
  27. }))
  28. return grpc.Dial(address, opts...)
  29. }
  30. func WithCachedGrpcClient(fn func(*grpc.ClientConn) error, address string, opts ...grpc.DialOption) error {
  31. grpcClientsLock.Lock()
  32. existingConnection, found := grpcClients[address]
  33. if found {
  34. grpcClientsLock.Unlock()
  35. return fn(existingConnection)
  36. }
  37. grpcConnection, err := GrpcDial(address, opts...)
  38. if err != nil {
  39. grpcClientsLock.Unlock()
  40. return fmt.Errorf("fail to dial %s: %v", address, err)
  41. }
  42. grpcClients[address] = grpcConnection
  43. grpcClientsLock.Unlock()
  44. err = fn(grpcConnection)
  45. if err != nil {
  46. grpcClientsLock.Lock()
  47. delete(grpcClients, address)
  48. grpcClientsLock.Unlock()
  49. }
  50. return err
  51. }