Created
November 27, 2017 15:12
-
-
Save axetroy/caf926ea60ad2a88f42900db0eef7406 to your computer and use it in GitHub Desktop.
Golang资源池
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
}() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
已发布一个库
https://github.com/axetroy/generic-pool