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
import (
"log"
"time"
"google.golang.org/grpc"
@ -10,6 +9,7 @@ import (
const (
// DefaultWriteTimeout is default value of Write Timeout
DefaultIdleTimeout = 0
DefaultMaxCapacity = 1
)
type (
@ -34,10 +34,12 @@ func (o *Options) Validate() *Options {
o.MaxIdle = 0
}
if o.MaxCapacity <= 0 {
log.Panicln("Max capacity of Pool must be greater than 0.")
o.MaxCapacity = DefaultMaxCapacity
}
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

14
pool.go
View File

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