Created
May 10, 2016 21:16
-
-
Save deankarn/196abcdfb63b5cd890427ba2beeec19c to your computer and use it in GitHub Desktop.
rpc ppol example
This file contains hidden or 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 client | |
| import ( | |
| "net/rpc" | |
| "github.com/go-playground/log" | |
| ) | |
| // NewFunc is the type of function that is called to create a new Go rpc Client | |
| type NewFunc func() *rpc.Client | |
| type clientsChan chan *rpc.Client | |
| // clientPool contains a contrained pool of *rpc.Client objects | |
| type clientPool struct { | |
| pool clientsChan | |
| newClient NewFunc | |
| max uint | |
| } | |
| // newPool creates and returns new ClientPool | |
| func newPool(max uint, fn NewFunc) *clientPool { | |
| if max == 0 { | |
| log.Warn("**** Warning invalid 'max' param, setting to 10 by default") | |
| } | |
| return &clientPool{ | |
| pool: make(clientsChan, max), | |
| newClient: fn, | |
| max: max, | |
| } | |
| } | |
| func (p *clientPool) Get() (c *rpc.Client) { | |
| select { | |
| case c = <-p.pool: | |
| default: | |
| if uint(len(p.pool)) == p.max { | |
| // if reached max number of allowed connections, must | |
| // wait until another gets put back into the pool instead | |
| // of creating new ones beyond the capacity of the machine | |
| // to handle. | |
| c = <-p.pool | |
| } else { | |
| c = p.newClient() | |
| } | |
| } | |
| return | |
| } | |
| func (p *clientPool) Put(c *rpc.Client) { | |
| select { | |
| case p.pool <- c: | |
| default: | |
| // eventual garbage collection | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment