out.go 1.5 KB

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