Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use channel to realize a connection pool in golang

Shulou Source: shulou.com Published: 2022-06-02 07:44:55 09月15日 Update

This article introduces how to use channel to achieve a connection pool in golang, the content is very detailed, interested friends can refer to, hope to be helpful to you.

What is universal?

The implementation of connection pool does not depend on a specific instance, but on an interface. The connection pool in this paper chooses the io.Closer interface, as long as the objects that implement this interface can be managed by the pool.

Of course, you can implement connection pooling based on interface {} so that any object can be managed.

Realization principle

The connection handle is stored in channel. Due to the nature of caching channel, if there is a connection in the pool, it will be returned directly. If there is no connection in the pool, it will block or create a new connection (if the maximum limit is not exceeded).

Because of interface-oriented programming, all the logic for creating connections is unclear, so you need to pass in a function that returns an io.Closer object.

Realize

Due to concurrency problems, locks are needed when mutually exclusive data in the operation pool is needed.

Package pool

Import (

"errors"

"io"

"sync"

"time"

)

Var (

ErrInvalidConfig = errors.New ("invalid pool config")

ErrPoolClosed = errors.New ("pool closed")

)

Type factory func () (io.Closer, error)

Type Pool interface {

Acquire () (io.Closer, error) / / get resources

Release (io.Closer) error / / release resources

Close (io.Closer) error / / close resources

Shutdown () error / / shuts down the pool

}

Type GenericPool struct {

Sync.Mutex

Pool chan io.Closer

Maximum number of resources in maxOpen int / / pool

NumOpen int / / number of resources in current pool

Minimum number of resources in minOpen int / / pool

Whether the closed bool / / pool is closed

MaxLifetime time.Duration

Factory factory / / method of creating a connection

}

Func NewGenericPool (minOpen, maxOpen int, maxLifetime time.Duration, factory factory) (* GenericPool, error) {

If maxOpen maxOpen {

Return nil, ErrInvalidConfig

}

P: = & GenericPool {

MaxOpen: maxOpen

MinOpen: minOpen

MaxLifetime: maxLifetime

Factory: factory

Pool: make (chan io.Closer, maxOpen)

}

For I: = 0; I < minOpen; iTunes + {

Closer, err: = factory ()

If err! = nil {

Continue

}

P.numOpenbones +

P.pool

Tags: Resources interfaces objects maximum content function single more help management good clear interest forepool principle handle instance boy partner situation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Shulou Information Shulou Tech Info Linux NVidia