golang的连接池例子

谢夜洛
2023-12-01

 

测试代码

package main

import (
    "github.com/jolestar/go-commons-pool"
    "fmt"
)

type MyPoolObject struct {
    Name string
}

type MyObjectFactory struct {
}

func (f *MyPoolObject) Print() {
    fmt.Println(f)
}

func (f *MyObjectFactory) MakeObject() (*pool.PooledObject, error) {
    return pool.NewPooledObject(&MyPoolObject{}), nil
}

func (f *MyObjectFactory) DestroyObject(object *pool.PooledObject) error {
    //do destroy
    return nil
}

func (f *MyObjectFactory) ValidateObject(object *pool.PooledObject) bool {
    //do validate
    return true
}

func (f *MyObjectFactory) ActivateObject(object *pool.PooledObject) error {
    //do activate
    return nil
}

func (f *MyObjectFactory) PassivateObject(object *pool.PooledObject) error {
    //do passivate
    return nil
}

func main() {
    pool := pool.NewObjectPoolWithDefaultConfig(pool.NewPooledObjectFactorySimple(
        func() (interface{}, error) {
            return &MyPoolObject{}, nil
        }))
    obj, _ := pool.BorrowObject()

    obj.(*MyPoolObject).Name = "1111"
    obj.(*MyPoolObject).Print()

    pool.ReturnObject(obj)
}

 

 类似资料: