GoDoc Go Report Card Build Status LICENSE

grpcpool is used to manage and reuse gRPc connections. You can limit the Usage amount for per connections.


go get -u


import ""


func main()  {
	// Create a new pool
	pool, err := grpcpool.New(func() (*grpc.ClientConn, error) {
		return grpc.Dial(addr, grpc.WithInsecure())
	}, 2, 5, 1000, time.Hour, 0)

	// Error handle
	if err != nil{
		log.Printf("Create gRPC pool:%v\n", err)

	// Release pool
	defer pool.Close()

	// Print the pool info

	// Get connection from the pool
	conn, err := pool.Get(context.Background())
	if err != nil {
		log.Printf("Get connection fail:%v", err)

	// Get connection from the pool with timeout
	ctx, _ := context.WithDeadline(context.Background(), time.Now().Add(time.Second))
	conn, err := pool.Get(ctx)
	if err != grpcpool.ErrTimeout {
		log.Printf("Time out")

	// Create a gRPC server client by conn
	client := pb.NewgRPCServerClient(conn.ClientConn)
	// Put back the Conn
Expand ▾ Collapse ▴




This section is empty.


var (
	// ErrClosed is the error when the client pool is closed
	ErrClosed = errors.New("client pool is closed")
	// ErrTimeout is the error when the client pool timed out
	ErrTimeout = errors.New("get client timed out")
	// ErrFullPool is the error when the pool is already full
	ErrFullPool = errors.New("can't create ClientConn into a full pool")

Error defined


This section is empty.


type ClientConn

type ClientConn struct {
	// contains filtered or unexported fields

ClientConn is the basic unit in the pool

func (*ClientConn) Put

func (client *ClientConn) Put()

Put return the ClientConn when client call finish

type Factory

type Factory func() (*grpc.ClientConn, error)

Factory function type to create a new gRPC client

type Options

type Options struct {
	Factory         Factory
	PoolSize        int
	MinIdleConns    int
	UsedPreConn     int
	MaxConnLifeTime time.Duration
	IdleTimeout     time.Duration

Options Pool Options defined

type Pool

type Pool struct {
	// contains filtered or unexported fields

Pool struct defined

func New

func New(factory Factory, minIdleConns, poolSize, usedPreConn int, idleTimeout, maxLifetime time.Duration) (*Pool, error)

New create and init a new gRPC pool

func (*Pool) Close

func (p *Pool) Close()

Close the pool and release resources

func (*Pool) CloseClient

func (p *Pool) CloseClient(client *ClientConn) error

CloseClient will remove the client And close it

func (*Pool) Get

func (p *Pool) Get(ctx context.Context) (*ClientConn, error)

Get an Available client to use

func (*Pool) Print

func (p *Pool) Print() []byte

Print the pool to monitor Usage