Skip to content

octu0/nats-pool

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

39 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.