golang通用连接池,支持GRPC,RPC,TCP

naiwenw 2019-07-01

pool

https://github.com/flyaways/pool

Pool 用于管理客户端到服务集群之间的连接.

Pool的主要功能:

  • 通用连接池 - Pool for GRPC,RPC,TCP.support RPC timeout.
  • 支持集群 - Connet to Cluster.
  • 动态更新 - Danamic update targets.

Pool runs on Linux, Mac OS X, and Windows.

声明:当前使用随机数策略达到动态负载均衡.

下载

go get -u gopkg.in/flyaways/pool.v1

导入方法

import "gopkg.in/flyaways/pool.v1"

使用示例

package main

import (
    "log"
    "time"

    "gopkg.in/flyaways/pool.v1"
    "google.golang.org/grpc"
)

func main() {
    options := &pool.Options{
        InitTargets:  []string{"127.0.0.1:8080"},
        InitCap:      5,
        MaxCap:       30,
        DialTimeout:  time.Second * 5,
        IdleTimeout:  time.Second * 60,
        ReadTimeout:  time.Second * 5,
        WriteTimeout: time.Second * 5,
    }

    //初始化连接池
    p, err := pool.NewGRPCPool(options, grpc.WithInsecure())

    if err != nil {
        log.Printf("%#v\n", err)
        return
    }

    if p == nil {
        log.Printf("p= %#v\n", p)
        return
    }

    defer p.Close()

    //动态更新服务地址
    //options.Input()<-&[]string{}

    conn, err := p.Get()
    if err != nil {
        log.Printf("%#v\n", err)
        return
    }

    defer p.Put(conn)

    //实现各种业务代码
    //conn.DoSomething()

    //打印空闲连接数
    log.Printf("len=%d\n", p.IdleCount())
}

参考

版权声明

  • The MIT License (MIT) - see LICENSE for more details

相关推荐