pool

package
v0.0.0-...-d31700d Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2022 License: MIT Imports: 8 Imported by: 0

README

sleep

A generic resource pool with maxOpen, maxIdle and usability checking.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type OpenFunc

type OpenFunc func(context.Context) (io.Closer, error)

the func to open a resource

type Pool

type Pool struct {
	sync.Mutex
	// contains filtered or unexported fields
}
Example
var pool, err = New(func(ctx context.Context) (io.Closer, error) {
	return net.Dial("tcp", "baidu.com:80")
}, func(ctx context.Context, r *Resource) bool {
	if time.Since(r.IdleAt) < time.Minute {
		return true
	}
	// check if r.Resource() is usable, may be by a ping or noop operation
	return true
}, 5, 2)
if err != nil {
	panic(err)
}

// this can also be doing concurrently
for i := 0; i < 10; i++ {
	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
	// get a connection
	resource, err := pool.Get(ctx)
	if err != nil {
		panic(err)
	}

	// do some work with the connection ...
	conn := resource.Resource().(net.Conn)
	conn.Write(nil)

	// put the connection back
	if err := pool.Put(resource); err != nil {
		panic(err)
	}
}
Output:

func New

func New(open OpenFunc, usable UsableFunc, maxOpen, maxIdle int) (*Pool, error)

func New2

func New2(open OpenFunc, usable UsableFunc, values url.Values) (*Pool, error)

New2 return a pool by params from url.Values. Params default value: maxOpen => 10; maxIdle => 1;

func (*Pool) Close

func (p *Pool) Close(r *Resource) error

Close a resource got from the pool. The resource must be got from the pool and be `Close`d only one time, otherwise an error is returned.

func (*Pool) Get

func (p *Pool) Get(ctx context.Context) (*Resource, error)

func (*Pool) Put

func (p *Pool) Put(r *Resource) error

Put a resource back into the pool. The resource must be got from the pool and be `Put` only one time, otherwise an error is returned.

type Resource

type Resource struct {
	io.Closer
	IdleAt   time.Time
	OpenedAt time.Time
}

func (*Resource) Resource

func (r *Resource) Resource() io.Closer

type UsableFunc

type UsableFunc func(context.Context, *Resource) bool

the func to check if a resource is usable.

Jump to

Keyboard shortcuts

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