ejfinneran / ratelimit

A Redis-backed rate limiter written in Ruby
MIT License
260 stars 57 forks source link

Making it possible to use a connection pool for getting a Redis instance #21

Open mikebaldry opened 8 years ago

mikebaldry commented 8 years ago

In some (most production, I'd have thought) projects you have a pool of Redis connections from which you can checkout a connection, perform your actions then put it back in to the pool ready for the next thing to use.

This is not possible with your current implementation so I've added an option checkout_redis_with, you can pass in a lambda which yields with the Redis connection.

looks like

Ratelimit.new("abc", checkout_redis_with: -> (&block) { MyRedisPool.checkout(&block) })

or similar.

The original implementation still works the same, but checks out a connection when it needs to use one.

I've also updated it to use MULTI instead of pipelining as expressed in a previous unanswered PR.

coveralls commented 8 years ago

Coverage Status

Coverage increased (+0.1%) to 99.259% when pulling 7d1156f8e70d4a7c46aae12d63539310308b83ab on Buyapowa:master into aa8bd7a71e263a86451a75216589d408fa133342 on ejfinneran:master.

coveralls commented 8 years ago

Coverage Status

Coverage increased (+0.1%) to 99.259% when pulling 7d1156f8e70d4a7c46aae12d63539310308b83ab on Buyapowa:master into aa8bd7a71e263a86451a75216589d408fa133342 on ejfinneran:master.

ejfinneran commented 8 years ago

Are there other Redis libraries that use this pattern? I'm wondering if supporting https://github.com/mperham/connection_pool might be cleaner/easier.

mikebaldry commented 8 years ago

@ejfinneran I did it in a specific way that allows that, you could do this:

redis_pool = ConnectionPool.new(size: 5, timeout: 5) { Redis::Client.new }

Ratelimit.new("blah", checkout_redis_with: &redis_pool.method(:with))

or as in the PR comment:

Ratelimit.new("blah", checkout_redis_with: -> (&block) { redis_pool.with(&block) })