Golang资源池

pool.go
复制

package pool

type CreatorFunc func() (interface{}, error)
type DestroyerFunc func(resource interface{}) (interface{}, error)

type Pool struct {
	config  Config
	options Options
	pool    []interface{}
}

type Config struct {
	Creator   CreatorFunc
	Destroyer DestroyerFunc
}

type Options struct {
	Min int
	Max int
}

/**
Create a new pool
 */
func New(c Config, o Options) (*Pool) {
	return &Pool{
		config:  c,
		options: o,
	}
}

/**
Get entity
 */
func (p *Pool) Get() (interface{}, error) {
	poolLength := len(p.pool)
	if poolLength < p.options.Min {
		if resource, err := p.config.Creator(); err != nil {
			return nil, err
		} else {
			p.pool = append(p.pool, resource)
			return resource, nil
		}
	} else if poolLength >= p.options.Min && poolLength <= p.options.Max {
		return nil, nil
	} else {
		return nil, nil
	}
}

/**
Release the resource
 */
func (p *Pool) Release() *Pool {
	return p
}

func main() {
	p := New(Config{
		// create connection
		Creator: func() (interface{}, error) {
			return 123, nil
		},
		// destroy connection
		Destroyer: func(connection interface{}) (interface{}, error) {
			return nil, nil
		},
	}, Options{Min: 0, Max: 5})

	p.Get()

	defer func() {
		p.Release()
	}()
}

大牛们的评论:朕有话说

还没有人评论哦,赶紧抢沙发!