1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- package proxy
- import (
- "log"
- "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 interface{}) bool { return true },
- Release: func(conn interface{}) {
- if conn != nil {
- conn.(net.Conn).SetDeadline(time.Now().Add(time.Millisecond))
- conn.(net.Conn).Close()
- }
- },
- InitialCap: InitialCap,
- MaxCap: MaxCap,
- Factory: func() (conn interface{}, err error) {
- conn, err = op.getConn()
- return
- },
- })
- if err != nil {
- log.Fatalf("init conn pool fail ,%s", err)
- } else {
- if InitialCap > 0 {
- log.Printf("init conn pool success")
- op.initPoolDeamon()
- } else {
- log.Printf("conn pool closed")
- }
- }
- return
- }
- func (op *OutPool) getConn() (conn interface{}, err error) {
- conn, err = ConnectHost(op.address, op.timeout)
- return
- }
- func (op *OutPool) initPoolDeamon() {
- go func() {
- if op.dur <= 0 {
- return
- }
- log.Printf("pool deamon started")
- for {
- time.Sleep(time.Second * time.Duration(op.dur))
- conn, err := op.getConn()
- if err != nil {
- log.Printf("pool deamon err %s , release pool", err)
- op.Pool.ReleaseAll()
- } else {
- conn.(net.Conn).SetDeadline(time.Now().Add(time.Millisecond))
- conn.(net.Conn).Close()
- }
- }
- }()
- }
|