• Stars
    star
    3,963
  • Rank 11,012 (Top 0.3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 15 years ago
  • Updated 2 months ago

Reviews

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

Repository Details

A Ruby client library for Redis

redis-rb Build Status Inline docs

A Ruby client that tries to match Redis' API one-to-one, while still providing an idiomatic interface.

See RubyDoc.info for the API docs of the latest published gem.

Getting started

Install with:

$ gem install redis

You can connect to Redis by instantiating the Redis class:

require "redis"

redis = Redis.new

This assumes Redis was started with a default configuration, and is listening on localhost, port 6379. If you need to connect to a remote server or a different port, try:

redis = Redis.new(host: "10.0.1.1", port: 6380, db: 15)

You can also specify connection options as a redis:// URL:

redis = Redis.new(url: "redis://:[email protected]:6380/15")

The client expects passwords with special chracters to be URL-encoded (i.e. CGI.escape(password)).

To connect to Redis listening on a Unix socket, try:

redis = Redis.new(path: "/tmp/redis.sock")

To connect to a password protected Redis instance, use:

redis = Redis.new(password: "mysecret")

To connect a Redis instance using ACL, use:

redis = Redis.new(username: 'myname', password: 'mysecret')

The Redis class exports methods that are named identical to the commands they execute. The arguments these methods accept are often identical to the arguments specified on the Redis website. For instance, the SET and GET commands can be called like this:

redis.set("mykey", "hello world")
# => "OK"

redis.get("mykey")
# => "hello world"

All commands, their arguments, and return values are documented and available on RubyDoc.info.

Connection Pooling and Thread safety

The client does not provide connection pooling. Each Redis instance has one and only one connection to the server, and use of this connection is protected by a mutex.

As such it is heavilly recommended to use the connection_pool gem, e.g.:

module MyApp
  def self.redis
    @redis ||= ConnectionPool::Wrapper.new do
      Redis.new(url: ENV["REDIS_URL"])
    end
  end
end

MyApp.redis.incr("some-counter")

Sentinel support

The client is able to perform automatic failover by using Redis Sentinel. Make sure to run Redis 2.8+ if you want to use this feature.

To connect using Sentinel, use:

SENTINELS = [{ host: "127.0.0.1", port: 26380 },
             { host: "127.0.0.1", port: 26381 }]

redis = Redis.new(name: "mymaster", sentinels: SENTINELS, role: :master)
  • The master name identifies a group of Redis instances composed of a master and one or more slaves (mymaster in the example).

  • It is possible to optionally provide a role. The allowed roles are master and slave. When the role is slave, the client will try to connect to a random slave of the specified master. If a role is not specified, the client will connect to the master.

  • When using the Sentinel support you need to specify a list of sentinels to connect to. The list does not need to enumerate all your Sentinel instances, but a few so that if one is down the client will try the next one. The client is able to remember the last Sentinel that was able to reply correctly and will use it for the next requests.

To authenticate Sentinel itself, you can specify the sentinel_username and sentinel_password. Exclude the sentinel_username option if you're using password-only authentication.

SENTINELS = [{ host: '127.0.0.1', port: 26380},
             { host: '127.0.0.1', port: 26381}]

redis = Redis.new(name: 'mymaster', sentinels: SENTINELS, sentinel_username: 'appuser', sentinel_password: 'mysecret', role: :master)

If you specify a username and/or password at the top level for your main Redis instance, Sentinel will not using thouse credentials

# Use 'mysecret' to authenticate against the mymaster instance, but skip authentication for the sentinels:
SENTINELS = [{ host: '127.0.0.1', port: 26380 },
             { host: '127.0.0.1', port: 26381 }]

redis = Redis.new(name: 'mymaster', sentinels: SENTINELS, role: :master, password: 'mysecret')

So you have to provide Sentinel credential and Redis explictly even they are the same

# Use 'mysecret' to authenticate against the mymaster instance and sentinel
SENTINELS = [{ host: '127.0.0.1', port: 26380 },
             { host: '127.0.0.1', port: 26381 }]

redis = Redis.new(name: 'mymaster', sentinels: SENTINELS, role: :master, password: 'mysecret', sentinel_password: 'mysecret')

Also the name, password, username and db for Redis instance can be passed as an url:

redis = Redis.new(url: "redis://appuser:mysecret@mymaster/10", sentinels: SENTINELS, role: :master)

Cluster support

Clustering. is supported via the redis-clustering gem.

Pipelining

When multiple commands are executed sequentially, but are not dependent, the calls can be pipelined. This means that the client doesn't wait for reply of the first command before sending the next command. The advantage is that multiple commands are sent at once, resulting in faster overall execution.

The client can be instructed to pipeline commands by using the #pipelined method. After the block is executed, the client sends all commands to Redis and gathers their replies. These replies are returned by the #pipelined method.

redis.pipelined do |pipeline|
  pipeline.set "foo", "bar"
  pipeline.incr "baz"
end
# => ["OK", 1]

Commands must be called on the yielded objects. If you call methods on the original client objects from inside a pipeline, they will be sent immediately:

redis.pipelined do |pipeline|
  pipeline.set "foo", "bar"
  redis.incr "baz" # => 1
end
# => ["OK"]

Exception management

The exception flag in the #pipelined is a feature that modifies the pipeline execution behavior. When set to false, it doesn't raise an exception when a command error occurs. Instead, it allows the pipeline to execute all commands, and any failed command will be available in the returned array. (Defaults to true)

results = redis.pipelined(exception: false) do |pipeline|
  pipeline.set('key1', 'value1')
  pipeline.lpush('key1', 'something') # This will fail
  pipeline.set('key2', 'value2')
end
# results => ["OK", #<RedisClient::WrongTypeError: WRONGTYPE Operation against a key holding the wrong kind of value>, "OK"]

results.each do |result|
  if result.is_a?(Redis::CommandError)
    # Do something with the failed result
  end
end

Executing commands atomically

You can use MULTI/EXEC to run a number of commands in an atomic fashion. This is similar to executing a pipeline, but the commands are preceded by a call to MULTI, and followed by a call to EXEC. Like the regular pipeline, the replies to the commands are returned by the #multi method.

redis.multi do |transaction|
  transaction.set "foo", "bar"
  transaction.incr "baz"
end
# => ["OK", 1]

Futures

Replies to commands in a pipeline can be accessed via the futures they emit. All calls on the pipeline object return a Future object, which responds to the #value method. When the pipeline has successfully executed, all futures are assigned their respective replies and can be used.

set = incr = nil
redis.pipelined do |pipeline|
  set = pipeline.set "foo", "bar"
  incr = pipeline.incr "baz"
end

set.value
# => "OK"

incr.value
# => 1

Error Handling

In general, if something goes wrong you'll get an exception. For example, if it can't connect to the server a Redis::CannotConnectError error will be raised.

begin
  redis.ping
rescue Redis::BaseError => e
  e.inspect
# => #<Redis::CannotConnectError: Timed out connecting to Redis on 10.0.1.1:6380>

  e.message
# => Timed out connecting to Redis on 10.0.1.1:6380
end

See lib/redis/errors.rb for information about what exceptions are possible.

Timeouts

The client allows you to configure connect, read, and write timeouts. Passing a single timeout option will set all three values:

Redis.new(:timeout => 1)

But you can use specific values for each of them:

Redis.new(
  :connect_timeout => 0.2,
  :read_timeout    => 1.0,
  :write_timeout   => 0.5
)

All timeout values are specified in seconds.

When using pub/sub, you can subscribe to a channel using a timeout as well:

redis = Redis.new(reconnect_attempts: 0)
redis.subscribe_with_timeout(5, "news") do |on|
  on.message do |channel, message|
    # ...
  end
end

If no message is received after 5 seconds, the client will unsubscribe.

Reconnections

By default, this gem will only retry a connection once and then fail, but the client allows you to configure how many reconnect_attempts it should complete before declaring a connection as failed.

Redis.new(reconnect_attempts: 0)
Redis.new(reconnect_attempts: 3)

If you wish to wait between reconnection attempts, you can instead pass a list of durations:

Redis.new(reconnect_attempts: [
  0, # retry immediately
  0.25, # retry a second time after 250ms
  1, # retry a third and final time after another 1s
])

If you wish to disable reconnection only for some commands, you can use disable_reconnection:

redis.get("some-key") # this may be retried
redis.disable_reconnection do
  redis.incr("some-counter") # this won't be retried.
end

SSL/TLS Support

To enable SSL support, pass the :ssl => true option when configuring the Redis client, or pass in :url => "rediss://..." (like HTTPS for Redis). You will also need to pass in an :ssl_params => { ... } hash used to configure the OpenSSL::SSL::SSLContext object used for the connection:

redis = Redis.new(
  :url        => "rediss://:[email protected]:6381/15",
  :ssl_params => {
    :ca_file => "/path/to/ca.crt"
  }
)

The options given to :ssl_params are passed directly to the OpenSSL::SSL::SSLContext#set_params method and can be any valid attribute of the SSL context. Please see the OpenSSL::SSL::SSLContext documentation for all of the available attributes.

Here is an example of passing in params that can be used for SSL client certificate authentication (a.k.a. mutual TLS):

redis = Redis.new(
  :url        => "rediss://:[email protected]:6381/15",
  :ssl_params => {
    :ca_file => "/path/to/ca.crt",
    :cert    => OpenSSL::X509::Certificate.new(File.read("client.crt")),
    :key     => OpenSSL::PKey::RSA.new(File.read("client.key"))
  }
)

Expert-Mode Options

  • inherit_socket: true: disable safety check that prevents a forked child from sharing a socket with its parent; this is potentially useful in order to mitigate connection churn when:

    • many short-lived forked children of one process need to talk to redis, AND
    • your own code prevents the parent process from using the redis connection while a child is alive

    Improper use of inherit_socket will result in corrupted and/or incorrect responses.

hiredis binding

By default, redis-rb uses Ruby's socket library to talk with Redis.

The hiredis driver uses the connection facility of hiredis-rb. In turn, hiredis-rb is a binding to the official hiredis client library. It optimizes for speed, at the cost of portability. Because it is a C extension, JRuby is not supported (by default).

It is best to use hiredis when you have large replies (for example: LRANGE, SMEMBERS, ZRANGE, etc.) and/or use big pipelines.

In your Gemfile, include hiredis-client:

gem "redis"
gem "hiredis-client"

If your application doesn't call Bundler.require, you may have to require it explictly:

require "hiredis-client"

This makes the hiredis driver the default.

If you want to be certain hiredis is being used, when instantiating the client object, specify hiredis:

redis = Redis.new(driver: :hiredis)

Testing

This library is tested against recent Ruby and Redis versions. Check Github Actions for the exact versions supported.

See Also

Contributors

Several people contributed to redis-rb, but we would like to especially mention Ezra Zygmuntowicz. Ezra introduced the Ruby community to many new cool technologies, like Redis. He wrote the first version of this client and evangelized Redis in Rubyland. Thank you, Ezra.

Contributing

Fork the project and send pull requests.

More Repositories

1

redis

Redis is an in-memory database that persists on disk. The data model is key-value, but many different kind of values are supported: Strings, Lists, Sets, Sorted Sets, Hashes, Streams, HyperLogLogs, Bitmaps.
C
66,732
star
2

go-redis

Redis Go client
Go
19,891
star
3

node-redis

Redis Node.js client
TypeScript
16,841
star
4

ioredis

๐Ÿš€ A robust, performance-focused, and full-featured Redis client for Node.js.
TypeScript
14,344
star
5

redis-py

Redis Python client
Python
12,506
star
6

jedis

Redis Java client
Java
11,766
star
7

hiredis

Minimalistic C client for Redis >= 1.2
C
6,197
star
8

lettuce

Advanced Java Redis client for thread-safe sync, async, and reactive usage. Supports Cluster, Sentinel, Pipelining, and codecs.
Java
5,352
star
9

rueidis

A fast Golang Redis client that supports Client Side Caching, Auto Pipelining, Generics OM, RedisJSON, RedisBloom, RediSearch, etc.
Go
2,327
star
10

redis-doc

Redis documentation source code for markdown and metadata files, conversion scripts, and so forth
Shell
2,310
star
11

redis-om-node

Object mapping, and more, for Redis and Node.js. Written in TypeScript.
TypeScript
1,158
star
12

docker-library-redis

Docker Official Image packaging for Redis
Shell
1,117
star
13

redis-om-python

Object mapping, and more, for Redis and Python
Python
1,093
star
14

redis-io

Application running http://redis.io
Ruby
637
star
15

redis-om-spring

Spring Data Redis extensions for better search, documents models, and more
Java
599
star
16

hiredis-py

Python wrapper for hiredis
C
495
star
17

redis-om-dotnet

Object mapping, and more, for Redis and .NET
C#
457
star
18

hiredis-rb

Ruby wrapper for hiredis
Ruby
319
star
19

hiredis-node

Node wrapper for hiredis
JavaScript
305
star
20

riot

๐Ÿงจ Get data in & out of Redis with RIOT
Java
273
star
21

NRedisStack

Redis Stack .Net client
C#
220
star
22

redis-vl-python

Redis Vector Library (RedisVL) interfaces with Redis' vector database for realtime semantic search, RAG, and recommendation systems.
Python
218
star
23

redis-rcp

Redis Change Proposals
136
star
24

redis-hashes

Redis tarball SHA1 hashes
92
star
25

lettucemod

Java client for Redis Modules
Java
50
star
26

spring-batch-redis

Spring Batch extension for Redis
Java
47
star
27

redis-specifications

A bin for Redis' specs
38
star
28

minipilot

MiniPilot is a GenAI-assisted chatbot backed by Redis. Chat with your documents
HTML
31
star
29

redis-benchmarks-specification

The Redis benchmarks specification describes the cross-language/tools requirements and expectations to foster performance and observability standards around redis related technologies. Members from both industry and academia, including organizations and individuals are encouraged to contribute.
Python
29
star
30

librdb

Redis RDB file parser, with JSON, RESP and RDB-loader extensions
C
23
star
31

docs

Documentation for Redis, Redis Cloud, and Redis Enterprise
Python
23
star
32

redis-debian

Debian packaging
Shell
18
star
33

redis-snap

A repository for snap packaging
10
star
34

redis-website

HTML
9
star
35

Redis-Insight-Guides

Learn modern data models and data processing tools bundled in Redis Stack to build real-time applications with the speed and stability of Redis.
5
star
36

redis-clinterwebz

Python
4
star
37

redis-extra-ci

4
star
38

riot-docker

Dockerfile
2
star
39

redis-rpm

Shell
2
star
40

scoop

1
star
41

homebrew-tap

Homebrew tap for Redis organization
Ruby
1
star