This commit is contained in:
crusader 2017-08-30 15:32:53 +09:00
parent 400587e73e
commit 15fe1864b3
2 changed files with 14 additions and 8 deletions

View File

@ -1,7 +1,6 @@
package overflow_grpc_pool package overflow_grpc_pool
import ( import (
"log"
"time" "time"
"google.golang.org/grpc" "google.golang.org/grpc"
@ -10,6 +9,7 @@ import (
const ( const (
// DefaultWriteTimeout is default value of Write Timeout // DefaultWriteTimeout is default value of Write Timeout
DefaultIdleTimeout = 0 DefaultIdleTimeout = 0
DefaultMaxCapacity = 1
) )
type ( type (
@ -34,10 +34,12 @@ func (o *Options) Validate() *Options {
o.MaxIdle = 0 o.MaxIdle = 0
} }
if o.MaxCapacity <= 0 { if o.MaxCapacity <= 0 {
log.Panicln("Max capacity of Pool must be greater than 0.") o.MaxCapacity = DefaultMaxCapacity
} }
if o.Creators == nil { if o.Creators == nil {
log.Panicln("Creators of Pool must be specified.") o.Creators = func() (*grpc.ClientConn, interface{}, error) {
return nil, nil, nil
}
} }
return o return o

14
pool.go
View File

@ -1,8 +1,8 @@
package overflow_grpc_pool package overflow_grpc_pool
import ( import (
"context"
"errors" "errors"
"log"
"time" "time"
"google.golang.org/grpc" "google.golang.org/grpc"
@ -29,14 +29,16 @@ type Pool interface {
} }
type pool struct { type pool struct {
ctx context.Context
options *Options options *Options
instances map[interface{}]*pooledInstance instances map[interface{}]*pooledInstance
instancesCh chan *pooledInstance instancesCh chan *pooledInstance
} }
func New(o *Options) (Pool, error) { func New(ctx context.Context, o *Options) (Pool, error) {
var err error var err error
p := &pool{ p := &pool{
ctx: ctx,
options: o.Validate(), options: o.Validate(),
instances: make(map[interface{}]*pooledInstance, o.MaxCapacity), instances: make(map[interface{}]*pooledInstance, o.MaxCapacity),
instancesCh: make(chan *pooledInstance, o.MaxCapacity), instancesCh: make(chan *pooledInstance, o.MaxCapacity),
@ -77,17 +79,19 @@ func (p *pool) createInstance() error {
return nil return nil
} }
func (p *pool) destroyInstance(i interface{}) { func (p *pool) destroyInstance(i interface{}) error {
var err error var err error
pi, ok := p.instances[i] pi, ok := p.instances[i]
if !ok { if !ok {
return return nil
} }
err = pi.clientConn.Close() err = pi.clientConn.Close()
if nil != err { if nil != err {
log.Printf("pool: ClientConn close error: %v", err) return err
} }
delete(p.instances, i) delete(p.instances, i)
return nil
} }
func (p *pool) get() (*pooledInstance, error) { func (p *pool) get() (*pooledInstance, error) {