pool

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2023 License: MIT Imports: 3 Imported by: 1

README

pool

common golang tcp connection pool, Get inspirations from sync.Pool

Features

Methods:
  • Get
  • Put
  • Len
  • Destroy
Attributes:
  • New
  • Ping
  • Close

you should set pool.New and pool.Close functions

Getting Started

Install:

go get -u github.com/go-baa/pool

Usage:

package main

import (
	"log"
	"net"

	"github.com/go-baa/pool"
)

func main() {
	// create, initialize cap, max cap, create function
	pl, err := pool.New(2, 10, func() interface{} {
		addr, _ := net.ResolveTCPAddr("tcp4", "127.0.0.1:8003")
		cli, err := net.DialTCP("tcp4", nil, addr)
		if err != nil {
			log.Fatalf("create client connection error: %v\n", err)
		}
		return cli
	})
	if err != nil {
		log.Fatalf("create pool error: %v\n", err)
	}

	pl.Ping = func(conn interface{}) bool {
		// check connection status
		return true
	}

	pl.Close = func(conn interface{}) {
		// close connection
		conn.(*net.TCPConn).Close()
	}

	// get conn from pool
	c, err := pl.Get()
	if err != nil {
		log.Printf("get client error: %v\n", err)
	}
	conn := c.(*net.TCPConn)
	conn.Write([]byte("PING"))
	result := make([]byte, 4)
	n, err := conn.Read(result)
	if err != nil || n < 4 {
		log.Printf("read data error: %v, size: %d\n", err, n)
	}
	log.Printf("got data: %s\n", result)

	// put, back for reuse
	pl.Put(conn)

	// len
	log.Printf("total connections: %d\n", pl.Len())

	// destroy, close all connections
	pl.Destroy()
}

you can find test server code in pool_test.go

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrClosed is the error resulting if the pool is closed via pool.Close().
	ErrClosed = errors.New("pool is closed")
)

Functions

This section is empty.

Types

type Pool

type Pool struct {
	// New create connection function
	New func() interface{}
	// Ping check connection is ok
	Ping func(interface{}) bool
	// Close close connection
	Close func(interface{})
	// contains filtered or unexported fields
}

Pool common connection pool

func New

func New(initCap, maxCap int, newFunc func() interface{}) (*Pool, error)

New create a pool with capacity

func (*Pool) Destroy

func (p *Pool) Destroy()

Destroy clear all connections

func (*Pool) Get

func (p *Pool) Get() (interface{}, error)

Get returns a conn form store or create one

func (*Pool) Len

func (p *Pool) Len() int

Len returns current connections in pool

func (*Pool) Put

func (p *Pool) Put(v interface{})

Put set back conn into store again

Jump to

Keyboard shortcuts

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