package proxy import ( "net" "time" ) type OutPool struct { Pool ConnPool dur int address string timeout int } func NewOutPool(dur int, address string, timeout int, InitialCap int, MaxCap int) (op OutPool) { op = OutPool{ dur: dur, address: address, timeout: timeout, } var err error op.Pool, err = NewConnPool(poolConfig{ IsActive: func(conn any) bool { return true }, Release: func(conn any) { if conn != nil { conn.(net.Conn).SetDeadline(time.Now().Add(time.Millisecond)) conn.(net.Conn).Close() } }, InitialCap: InitialCap, MaxCap: MaxCap, Factory: func() (conn any, err error) { conn, err = op.getConn() return }, }) if err != nil { logger.Sugar().Errorf("init conn pool fail ,%s", err) } else { if InitialCap > 0 { logger.Sugar().Infof("init conn pool success") op.initPoolDeamon() } else { logger.Sugar().Infof("conn pool closed") } } return } func (op *OutPool) getConn() (conn any, err error) { conn, err = ConnectHost(op.address, op.timeout) return } func (op *OutPool) initPoolDeamon() { go func() { if op.dur <= 0 { return } logger.Sugar().Infof("pool deamon started") for { time.Sleep(time.Second * time.Duration(op.dur)) conn, err := op.getConn() if err != nil { logger.Sugar().Infof("pool deamon err %s , release pool", err) op.Pool.ReleaseAll() } else { conn.(net.Conn).SetDeadline(time.Now().Add(time.Millisecond)) conn.(net.Conn).Close() } } }() }