go 语言连接池

Golang
422
0
0
2022-11-11
标签   Golang进阶

因为项目需求,需要用到连接池,在看了很多代码之后发现不能满足需求,所以自己撸一个,现在开源出来,看能否帮到跟我有同意需求的同学

仓库地址: github.com/bean-du/pool

欢迎大家 Star 和 Issuse

支持:

  1. DialerFunc 通过此func 定义需要管理的连接类型
  2. ReadFunc 根据连接类型自定义数据读取函数
  3. WriteFunc 根据连接类型自定义数据写入函数
  4. KeepaliveFunc 根据连接类型自定义心跳

使用示例:

package main

import (
    "context" 
    "github.com/bean-du/pool" 
    "log" 
    "os" 
    "os/signal" 
    "time"
)

func main() {

    sig := make(chan os.Signal, 1)
    signal.Notify(sig, os.Interrupt, os.Kill)

    // init a pool with options
    client := pool.NewClient(
        pool.WebsocketDialer("ws://127.0.0.1:8081/ws"),
        // set pool size
        pool.WithPoolSize(50),
        // set write func default is tcp writer
        pool.WithWriteFunc(pool.WsWriter),
        // set read func, must be set
        pool.WithReadFunc(pool.WebsocketReadFunc(dataHandleFunc)),
        // set min idle connections
        pool.WithMinIdleConns(10),
        // set idle check duration
        pool.WithIdleCheckFrequency(time.Second*10),
    )

    for i := 0; i < 10; i++ {
        go func() {
            if err := client.Send(context.Background(), []byte("hello")); err != nil {
                log.Println(err)
            }
        }()
    }

    select {
    case <-sig:
        client.Close()
    }
}

func dataHandleFunc(p []byte) {
    go func() {
        log.Println(string(p))
    }()
}