• Stars
    star
    1,627
  • Rank 28,754 (Top 0.6 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 13 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Generic connection pooling for Ruby

connection_pool

Build Status

Generic connection pooling for Ruby.

MongoDB has its own connection pool. ActiveRecord has its own connection pool. This is a generic connection pool that can be used with anything, e.g. Redis, Dalli and other Ruby network clients.

Usage

Create a pool of objects to share amongst the fibers or threads in your Ruby application:

$memcached = ConnectionPool.new(size: 5, timeout: 5) { Dalli::Client.new }

Then use the pool in your application:

$memcached.with do |conn|
  conn.get('some-count')
end

If all the objects in the connection pool are in use, with will block until one becomes available. If no object is available within :timeout seconds, with will raise a ConnectionPool::TimeoutError (a subclass of Timeout::Error).

You can also use ConnectionPool#then to support both a connection pool and a raw client.

# Compatible with a raw Redis::Client, and ConnectionPool Redis
$redis.then { |r| r.set 'foo' 'bar' }

Optionally, you can specify a timeout override using the with-block semantics:

$memcached.with(timeout: 2.0) do |conn|
  conn.get('some-count')
end

This will only modify the resource-get timeout for this particular invocation. This is useful if you want to fail-fast on certain non-critical sections when a resource is not available, or conversely if you are comfortable blocking longer on a particular resource. This is not implemented in the ConnectionPool::Wrapper class.

Migrating to a Connection Pool

You can use ConnectionPool::Wrapper to wrap a single global connection, making it easier to migrate existing connection code over time:

$redis = ConnectionPool::Wrapper.new(size: 5, timeout: 3) { Redis.new }
$redis.sadd('foo', 1)
$redis.smembers('foo')

The wrapper uses method_missing to checkout a connection, run the requested method and then immediately check the connection back into the pool. It's not high-performance so you'll want to port your performance sensitive code to use with as soon as possible.

$redis.with do |conn|
  conn.sadd('foo', 1)
  conn.smembers('foo')
end

Once you've ported your entire system to use with, you can simply remove Wrapper and use the simpler and faster ConnectionPool.

Shutdown

You can shut down a ConnectionPool instance once it should no longer be used. Further checkout attempts will immediately raise an error but existing checkouts will work.

cp = ConnectionPool.new { Redis.new }
cp.shutdown { |c| c.close }

Shutting down a connection pool will block until all connections are checked in and closed. Note that shutting down is completely optional; Ruby's garbage collector will reclaim unreferenced pools under normal circumstances.

Reload

You can reload a ConnectionPool instance in the case it is desired to close all connections to the pool and, unlike shutdown, afterwards recreate connections so the pool may continue to be used. Reloading may be useful after forking the process.

cp = ConnectionPool.new { Redis.new }
cp.reload { |conn| conn.quit }
cp.with { |conn| conn.get('some-count') }

Like shutdown, this will block until all connections are checked in and closed.

Current State

There are several methods that return information about a pool.

cp = ConnectionPool.new(size: 10) { Redis.new }
cp.size # => 10
cp.available # => 10

cp.with do |conn|
  cp.size # => 10
  cp.available # => 9
end

Notes

  • Connections are lazily created as needed.
  • There is no provision for repairing or checking the health of a connection; connections should be self-repairing. This is true of the Dalli and Redis clients.
  • WARNING: Don't ever use Timeout.timeout in your Ruby code or you will see occasional silent corruption and mysterious errors. The Timeout API is unsafe and cannot be used correctly, ever. Use proper socket timeout options as exposed by Net::HTTP, Redis, Dalli, etc.

Author

Mike Perham, @getajobmike, https://www.mikeperham.com

More Repositories

1

sidekiq

Simple, efficient background processing for Ruby
Ruby
12,059
star
2

inspeqtor

Monitor your application infrastructure!
Go
1,657
star
3

girl_friday

Have a task you want to get done but don't want to do it yourself? Give it to girl_friday!
Ruby
606
star
4

rack-fiber_pool

Rack middleware to execute each request in a Fiber
Ruby
244
star
5

bayes_motel

Multi-variate Bayesian classification engine
Ruby
190
star
6

evented

Your source for event-drivenness!
Ruby
172
star
7

phat

Asynchronous Rails!
Ruby
95
star
8

em_postgresql

ActiveRecord driver for Postgresql with EventMachine
Ruby
65
star
9

kuiq

Sidekiq desktop app
Ruby
55
star
10

inspeqtor-pro

Modern service monitoring, business edition.
Go
52
star
11

politics

Utilities and Algorithms for Distributed Processing.
Ruby
47
star
12

qanat

Fiber-based, highly concurrent MQ processor for Ruby
Ruby
39
star
13

chrono.js

Application metrics, webscale!
JavaScript
22
star
14

job_roundup

Benchmarking various background job engines
Ruby
17
star
15

bloaty_mcbloatface

"Oh my, you've put on some weight..."
Ruby
12
star
16

acting_lessons

Abusing Rubinius's Actors for fun and profit
Ruby
10
star
17

phony_baloney

Create fake servers for testing purposes
Ruby
10
star
18

gobox

How to use Golang's NaCl crypto API
Go
10
star
19

breakout

The classic Breakout game
Ruby
9
star
20

dotfiles

my dotfiles
Shell
7
star
21

blog

My blargh!
HTML
7
star
22

switch_redis

Ruby
7
star
23

discontent

The forum for terrible people
Ruby
7
star
24

sidekiq-websockets

Ruby
7
star
25

dotenv

Load contents of .env into child processes
Go
6
star
26

resque-client.go

Resque worker/client, written in Go
Go
6
star
27

contribsys.com

contribsys.com
CSS
5
star
28

edistuff

EDI parser and generation code
Java
5
star
29

queso

Query anything!
Ruby
5
star
30

gem_dir

Adds the 'gem dir' command to RubyGems to display the root directory of a given gem.
Ruby
4
star
31

tracknowledge

Race Tracks Galore!
Ruby
4
star
32

aoc2016

Advent of Code 2016
Ruby
4
star
33

right_aws

RightScale's right_aws 1.10.0 gem with fixes
Ruby
3
star
34

minesweeper

Minesweeper for MacRuby
3
star
35

docdb_shootout

Document-oriented database comparision
Ruby
3
star
36

news_flash

Show your users the latest news
Ruby
2
star
37

slice

My slice configuration
Ruby
1
star
38

perham.net

HTML
1
star