out.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package proxy
  2. import (
  3. "net"
  4. "time"
  5. )
  6. type OutPool struct {
  7. Pool ConnPool
  8. dur int
  9. address string
  10. timeout int
  11. }
  12. func NewOutPool(dur int, address string, timeout int, InitialCap int, MaxCap int) (op OutPool) {
  13. op = OutPool{
  14. dur: dur,
  15. address: address,
  16. timeout: timeout,
  17. }
  18. var err error
  19. op.Pool, err = NewConnPool(poolConfig{
  20. IsActive: func(conn any) bool { return true },
  21. Release: func(conn any) {
  22. if conn != nil {
  23. conn.(net.Conn).SetDeadline(time.Now().Add(time.Millisecond))
  24. conn.(net.Conn).Close()
  25. }
  26. },
  27. InitialCap: InitialCap,
  28. MaxCap: MaxCap,
  29. Factory: func() (conn any, err error) {
  30. conn, err = op.getConn()
  31. return
  32. },
  33. })
  34. if err != nil {
  35. logger.Sugar().Errorf("init conn pool fail ,%s", err)
  36. } else {
  37. if InitialCap > 0 {
  38. logger.Sugar().Infof("init conn pool success")
  39. op.initPoolDeamon()
  40. } else {
  41. logger.Sugar().Infof("conn pool closed")
  42. }
  43. }
  44. return
  45. }
  46. func (op *OutPool) getConn() (conn any, err error) {
  47. conn, err = ConnectHost(op.address, op.timeout)
  48. return
  49. }
  50. func (op *OutPool) initPoolDeamon() {
  51. go func() {
  52. if op.dur <= 0 {
  53. return
  54. }
  55. logger.Sugar().Infof("pool deamon started")
  56. for {
  57. time.Sleep(time.Second * time.Duration(op.dur))
  58. conn, err := op.getConn()
  59. if err != nil {
  60. logger.Sugar().Infof("pool deamon err %s , release pool", err)
  61. op.Pool.ReleaseAll()
  62. } else {
  63. conn.(net.Conn).SetDeadline(time.Now().Add(time.Millisecond))
  64. conn.(net.Conn).Close()
  65. }
  66. }
  67. }()
  68. }