安裝:
go get -v -u github.com/rocket049/connpool
go get -v -u gitee.com/rocket049/connpool
rocket049/connpool
包是本人用go語言開發(fā)的提陶,提供一個通用的TCP連接池吆豹,初始化參數(shù)包括最高連接數(shù)微姊、超時秒數(shù)匙铡、連接函數(shù),放回連接池的連接被重新取出時,如果已經超時,將會自動重新連接出爹;如果沒有超時,連接將被復用缎除。
可調用的函數(shù):
type Conn
func (s *Conn) Read(p []byte) (int, error)
func (s *Conn) Write(p []byte) (int, error)
func (s *Conn) Close() error
func (s *Conn) Timeout() bool
type Pool
func NewPool(max, timeout int, factory func() (net.Conn, error)) *Pool
func (s *Pool) Get() (*Conn, error)
func (s *Pool) Put(conn1 *Conn)
func (s *Pool) Close()
調用示例:
import "gitee.com/rocket049/connpool"
func factory() (net.Conn,error) {
return net.Dial("tcp","127.0.0.1:7060")
}
func UsePool() {
// 設置連接池大小為10,超時秒數(shù)為30,連接函數(shù)為 factory
pool1 := connpool.NewPool(10, 30 ,factory)
defer pool1.Close()
var wg sync.WaitGroup
for i:=0;i<50;i++ {
wg.Add(1)
go func(n int){
// 取出連接
conn ,err := pool1.Get()
if err!=nil {
...
}
//發(fā)送數(shù)據
_,err = conn.Write( msg )
if err!=nil{
...
}
//讀取數(shù)據
n1,err := conn.Read( buf )
if err!=nil{
...
}
//超時檢測和重連
if conn.Timeout() {
pool1.Put(conn)
conn ,err := pool1.Get()
...
}
//放回連接池
pool1.Put(conn)
wg.Done()
}(i)
}
wg.Wait()
}