企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
对象池 场景:数据库连接池 ~~~ type DBConnection struct { index int } type DBConnectionPool struct { conQueue chan *DBConnection } /** 创建对象池 */ func CreateDBConnectionPool(maxNum int) *DBConnectionPool { objPool := DBConnectionPool{} objPool.conQueue = make(chan *DBConnection, maxNum) for i := 0; i < maxNum; i++ { con := new(DBConnection) con.index = i fmt.Printf("connection address:%p , value:%v \n", con, con.index) objPool.conQueue <- &DBConnection{} } fmt.Println("Object pool created") return &objPool } /** 获取对象 */ func (pool *DBConnectionPool) GetConnect(timeOut time.Duration) (*DBConnection, error) { select { case con := <-pool.conQueue: return con, nil case <-time.After(timeOut): return nil, errors.New("get connection time out") } } func (pool *DBConnectionPool) ReleaseConnect(con *DBConnection) error { select { case pool.conQueue <- con: return nil default: return errors.New("overflow") } } func TestConnectPoolMock(t *testing.T) { pool := CreateDBConnectionPool(10) for i := 1; i <= 20; i++ { go func(transId int) { con, err := pool.GetConnect(time.Millisecond * 200) if err != nil { t.Log("get connection failed") } fmt.Printf("do something:%v, onnection type:%T, address:%p \n", transId, con, con) time.Sleep(300 * time.Millisecond) pool.ReleaseConnect(con) }(i) } time.Sleep(3 * time.Second) } ~~~