connpool

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2022 License: MIT Imports: 6 Imported by: 0

README

Server Example

Client Dial using connections pool Example

这个是什么

这个是一个客户端的连接池。其原理就是建立一个简单的线程安全队列,提前建立好MIN_SIZE(默认128个)个连接,当调用Read()或者Write()函数的时候,会从队列中取一个,然后写入或者读取,然后再放回队列中,方便下一次复用。只有当你调用Close()函数,建立的连接才能被安全的关闭。

为什么要这么设计

1.允许在不同goroutine中对TCP连接进行Read,Write。也就是说,你不必再拘束于一个TCP连接,你可以同时写入多个或者读取多个,而且这是线程安全的。(为什么?因为每个连接都是独立的,互不影响)

2.上述并发读写很美妙,但是会出现一个问题,当goroutine太多,超过系统HARD LIMIT/SOFT LIMIT时候,触发Too many open files等错误,为解决此问题,连接池会限制最大连接数,当池子中已经没有可用连接,会等候连接入队进行重利用,当超过TIMEOUT时间后,仍没有入队连接,会尝试建立连接。

Documentation

Index

Constants

View Source
const (
	MIN_SIZE = 128
)

Variables

This section is empty.

Functions

func GetSysMax

func GetSysMax() int32

func Wrapper

func Wrapper(p *Pool) net.Conn

Types

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

func (*Conn) Close

func (cn *Conn) Close() error

func (*Conn) LocalAddr

func (cn *Conn) LocalAddr() net.Addr

func (*Conn) Read

func (cn *Conn) Read(b []byte) (n int, err error)

func (*Conn) RemoteAddr

func (cn *Conn) RemoteAddr() net.Addr

func (*Conn) SetDeadline

func (cn *Conn) SetDeadline(t time.Time) error

func (*Conn) SetReadDeadline

func (cn *Conn) SetReadDeadline(t time.Time) error

func (*Conn) SetWriteDeadline

func (cn *Conn) SetWriteDeadline(t time.Time) error

func (*Conn) Write

func (cn *Conn) Write(b []byte) (n int, err error)

type Opts

type Opts []interface{}

func DefaultOpts

func DefaultOpts() Opts

func (Opts) Parse

func (o Opts) Parse() (*net.Dialer, time.Duration, int32, context.Context)

func (Opts) WithContext

func (o Opts) WithContext(c context.Context)

func (Opts) WithDialer

func (o Opts) WithDialer(d *net.Dialer)

func (Opts) WithMinSize

func (o Opts) WithMinSize(m int32)

func (Opts) WithTimeout

func (o Opts) WithTimeout(t time.Duration)

type Pool

type Pool struct {
	Deadline struct {
		// contains filtered or unexported fields
	}
	// contains filtered or unexported fields
}

func New

func New(remoteAddr string, opts Opts) *Pool

func (*Pool) Close

func (p *Pool) Close()

func (*Pool) Flush

func (p *Pool) Flush()

Flush dequeues all TCP Connections and close them.

func (*Pool) Get

func (p *Pool) Get() (net.Conn, error)

Get one TCP connection from the pool.

If the connection reaches the max limit, poll until one enqueue during TIMEOUT.

If not, set up a new one

func (*Pool) Len

func (p *Pool) Len() int32

func (*Pool) Put

func (p *Pool) Put(c net.Conn)

Put the TCP connection into the pool.

func (*Pool) SetDeadline

func (p *Pool) SetDeadline(t time.Time)

func (*Pool) SetReadDeadline

func (p *Pool) SetReadDeadline(t time.Time)

func (*Pool) SetWriteDeadline

func (p *Pool) SetWriteDeadline(t time.Time)

Jump to

Keyboard shortcuts

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