rpc连接过多浪费资源,循环利用
package rpc
import (
"sync"
)
var rpcClientPoolMap map[string]*connPool
func init() {
rpcClientPoolMap = make(map[string]*connPool)
}
type connPool struct {
name string
MaxConnCount int
poolCap int
mu sync.Mutex
clientPool chan *PaymentClient
}
func PopClientFromPool(name string) *PaymentClient {
for k, v := range rpcClientPoolMap {
if k == name {
return v.popConn()
}
}
pool := &connPool{}
pool.name = name
pool.MaxConnCount = 3
pool.clientPool = make(chan *PaymentClient, pool.MaxConnCount)
rpcClientPoolMap[name] = pool
return pool.popConn()
}
func PushClientToPool(cli *PaymentClient) {
for k, v := range rpcClientPoolMap {
if k == cli.name {
v.pushConn(cli)
return
}
}
}
func (c *connPool) popConn() *PaymentClient {
if len(c.clientPool) == 0 {
c.mu.Lock()
defer c.mu.Unlock()
if c.poolCap < c.MaxConnCount {
return c.addConn()
}
}
return <-c.clientPool
}
func (c *connPool) addConn() *PaymentClient {
c.poolCap++
return NewRPCClient(c.name)
}
func (c *connPool) pushConn(cli *PaymentClient) {
c.clientPool <- cli
}