grpc_conn_pool

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 27, 2023 License: MIT Imports: 6 Imported by: 0

README

go grpc 连接池

Go Reference

golang grpc client pool

特点

  • 支持多target,pool.
  • 连接检测,失效,才进行替换连接
  • 获得一次连接耗时 90 op/ns 左右(15年mac pro)

使用

package grpc_conn_pool_test

import (
	"net"
	"testing"
	"time"

	"github.com/cr-mao/grpc-conn-pool"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func Test_GrpcConnPool(t *testing.T) {

	target := "127.0.0.1:13688"
	go func() {
		clientBuilder := grpc_conn_pool.NewClientBuilder(&grpc_conn_pool.Options{
			PoolSize: 20,
			DialOpts: []grpc.DialOption{
				grpc.WithTransportCredentials(insecure.NewCredentials()),
			},
		})

		i := 0
		begin := time.Now()
		for {
			conn, err := clientBuilder.GetConn(target)
			if err != nil {
				t.Errorf("get conn err %v", err)
				return
			}
			err = grpc_conn_pool.CheckState(conn)
			if err != nil {
				t.Log(conn.GetState())
			}
			//time.Sleep(time.Millisecond * 2)
			//t.Log("ok")
			i++
			if i > 1000000 {
				break
			}
		}
		// 10000次 只要7ms.
		cost := time.Now().Sub(begin).Nanoseconds()
		t.Log(cost)
		t.Logf("%d ns/op", cost/1000000) // 730 op/ns
	}()

	addr := "0.0.0.0:13688"

	lis, err := net.Listen("tcp", addr)
	if err != nil {
		t.Fatalf("Listen err :%v", err)
	}
	t.Logf("grpc serve at: %s", addr)
	server := grpc.NewServer()
	_ = server.Serve(lis)

}

Documentation

Overview

* User: cr-mao Date: 2023/8/27 08:53 Email: crmao@qq.com Desc: pool.go

Index

Constants

This section is empty.

Variables

View Source
var ErrConn = errors.New("grpc conn has error Shutdown or TransientFailure")

Functions

func CheckState

func CheckState(conn *grpc.ClientConn) error

检测连接是否正常

Types

type ClientBuilder

type ClientBuilder struct {
	// contains filtered or unexported fields
}

func NewClientBuilder

func NewClientBuilder(opts *Options) *ClientBuilder

func (*ClientBuilder) GetConn

func (b *ClientBuilder) GetConn(target string) (*grpc.ClientConn, error)

Build 构建连接

type Options

type Options struct {
	PoolSize uint32
	DialOpts []grpc.DialOption
}

type Pool

type Pool struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*Pool) Get

func (p *Pool) Get() (*grpc.ClientConn, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL