Skip to content

Instantly share code, notes, and snippets.

@axetroy
Created November 27, 2017 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axetroy/caf926ea60ad2a88f42900db0eef7406 to your computer and use it in GitHub Desktop.
Save axetroy/caf926ea60ad2a88f42900db0eef7406 to your computer and use it in GitHub Desktop.
Golang资源池
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()
}()
}
@axetroy
Copy link
Author

axetroy commented Nov 30, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment