grpc_client_pool.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package utils
  2. import (
  3. "google.golang.org/grpc"
  4. "google.golang.org/grpc/connectivity"
  5. "sync"
  6. )
  7. type ClientPool interface {
  8. Get() *grpc.ClientConn
  9. Put(conn *grpc.ClientConn)
  10. }
  11. type clientPool struct {
  12. pool sync.Pool
  13. }
  14. func GetPoolInstance(target string, opts ...grpc.DialOption) (ClientPool, error) {
  15. return &clientPool{
  16. pool: sync.Pool{
  17. New: func() any {
  18. conn, err := grpc.NewClient(target, opts...)
  19. if err != nil {
  20. FileLog.Error("连接sso登录服务失败:%v", err)
  21. }
  22. return conn
  23. },
  24. },
  25. }, nil
  26. }
  27. func (c *clientPool) Get() *grpc.ClientConn {
  28. conn := c.pool.Get().(*grpc.ClientConn)
  29. // 当连接不可用时,关闭当前连接,并新建一个连接
  30. if conn.GetState() == connectivity.Shutdown || conn.GetState() == connectivity.TransientFailure {
  31. conn.Close()
  32. conn = c.pool.New().(*grpc.ClientConn)
  33. }
  34. return conn
  35. }
  36. func (c *clientPool) Put(conn *grpc.ClientConn) {
  37. // 当连接不可用时,关闭当前连接,并不再放回池中
  38. if conn.GetState() == connectivity.Shutdown || conn.GetState() == connectivity.TransientFailure {
  39. conn.Close()
  40. return
  41. }
  42. c.pool.Put(conn)
  43. }