connectionpool

package module
v0.2.7 Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2024 License: MIT Imports: 4 Imported by: 1

README

connection-pool

Universal connection pool on generics.

Feature:
  • More versatile, The connection type in the connection pool is generic, making it more versatile.
  • More configurable, The connection supports setting the maximum idle time, the timeout connection will be closed and discarded, which can avoid the problem of automatic connection failure when idle.
  • Support user setting ping method, used to check the connectivity of connection, invalid connection will be discarded.
  • Support connection waiting, When the connection pool is full, support for connection waiting.
Install
go get github.com/sschekotikhin/connection-pool
Example:
package main

import (
	"log"
	"time"

	connectionpool "github.com/sschekotikhin/connection-pool"
)

type Conn struct{}

func (c Conn) Ping() error {
	return nil
}

func (c Conn) Close() error {
	return nil
}

func main() {
	pool, err := connectionpool.New(
		&connectionpool.Config[Conn]{
			MinConns:    10,
			MaxConns:    50,
			IdleTimeout: 10 * time.Second,
			Factory: func() (Conn, error) {
				return Conn{}, nil
			},
		},
	)
	if err != nil {
		log.Fatal(err)
	}
	defer pool.Close()

        // get connection from the pool
	conn, err := pool.Connection()
	if err != nil {
		log.Fatal(err)
	}
	// do something with received connection
        // return connection to the pool
	pool.Put(conn)
}
Remarks:

The connection pool implementation refers to pool https://github.com/silenceper/pool, thanks.


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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config[T Connectable] struct {
	// Min number of connections that will be opened during New() function.
	MinConns int
	// Max number of opened connections.
	MaxConns int
	// IDLE timeout for every connection.
	IdleTimeout time.Duration
	// Function for creating new connections.
	Factory func() (T, error)
}

type Connectable

type Connectable interface {
	Ping() error
	Close() error
}

type ConnectionPool

type ConnectionPool[T Connectable] interface {
	// Returns number of opened connections.
	Len() int
	// Retrieves connection from pool if it exists or opens new connection.
	Connection(ctx context.Context) (T, error)
	// Returns connection to pool.
	Put(conn T) error
	// Closes all connections and pool.
	Close() error
}

func New

func New[T Connectable](cfg *Config[T]) (ConnectionPool[T], error)

Opens new connection pool.

Jump to

Keyboard shortcuts

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