pool

package module
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2020 License: Apache-2.0 Imports: 2 Imported by: 1

README

nats-pool

Apache License GoDoc Go Report Card Releases

nats-pool connection pooling for nats.go

Installation

go get github.com/octu0/nats-pool

Example

import (
	"github.com/nats-io/nats.go"
	"github.com/octu0/nats-pool"
)

var (
	// 100 connections pool
	connPool = pool.New(100, "nats://localhost:4222",
		nats.NoEcho(),
		nats.Name("client/1.0"),
		nats.ErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) {
			...
		}),
	)
)

func main() {
	nc, err := connPool.Get()
	if err != nil {
		panic(err)
	}
	// release *nats.Conn to pool
	defer connPool.Put(nc)
	:
	nc.Subscribe("subject.a.b.c", func(msg *nats.Msg) {
		...
	})
	nc.Publish("foo.bar", []byte("hello world"))
}

Benchmark

Here are the benchmark results for a simple case with multiple PubSub.

$ go test -bench=. -benchmem
goos: darwin
goarch: amd64
pkg: github.com/octu0/nats-pool
BenchmarkSimpleConnPubSub/NoPool-8         	    5000	    261422 ns/op	  124696 B/op	     177 allocs/op
BenchmarkSimpleConnPubSub/UsePool-8        	   35050	     29524 ns/op	    4656 B/op	      50 allocs/op
PASS
ok  	github.com/octu0/nats-pool	3.829s

License

Apache 2.0, see LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	Version string = "1.0.6"
)

Version of release

Variables

This section is empty.

Functions

This section is empty.

Types

type ConnPool

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

ConnPool implements pool of *nats.Conn of a bounded channel

func New

func New(poolSize int, url string, options ...nats.Option) *ConnPool

New create new ConnPool bounded to the given poolSize, with specify the URL string to connect to natsd on url. option is used for nats#Connect when creating pool connections

func (*ConnPool) Cap

func (p *ConnPool) Cap() int

Cap returns the number of pool capacity

func (*ConnPool) DisconnectAll added in v1.0.5

func (p *ConnPool) DisconnectAll()

DisconnectAll close all connected *nats.Conn connections in pool

func (*ConnPool) Get

func (p *ConnPool) Get() (*nats.Conn, error)

Get returns *nats.Conn, if connection is available, or makes a new connection and returns a value if not. if *nats.Conn is not connected in pool, make new connection in the same way.

func (*ConnPool) Len

func (p *ConnPool) Len() int

Len returns the number of items currently pooled

func (*ConnPool) Put

func (p *ConnPool) Put(nc *nats.Conn) (bool, error)

Put puts *nats.Conn back into the pool. there is no need to do Close() ahead of time, ConnPool will automatically do a Close() if it cannot be returned to the pool.

Jump to

Keyboard shortcuts

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