Simple low level client for Redis 6+
redis-client is a simple, low-level, client for Redis 6+, Valkey 7+, KeyDB,
and several other databases that implement the same RESP3 protocol.
Contrary to the redis gem, redis-client doesn't try to map all Redis commands to Ruby constructs,
it merely is a thin wrapper on top of the RESP3 protocol.
Add this line to your application's Gemfile:
gem 'redis-client'And then execute:
$ bundle installOr install it yourself as:
$ gem install redis-clientTo use RedisClient you first define a connection configuration, from which you can create a connection pool:
redis_config = RedisClient.config(host: "10.0.1.1", port: 6380, db: 15)
redis = redis_config.new_pool(timeout: 0.5, size: Integer(ENV.fetch("RAILS_MAX_THREADS", 5)))
redis.call("PING") # => "PONG"If you are issuing multiple commands in a raw, but can't pipeline them, it's best to use #with to avoid going through the connection checkout
several times:
redis.with do |r|
r.call("SET", "mykey", "hello world") # => "OK"
r.call("GET", "mykey") # => "hello world"
endIf you are working in a single-threaded environment, or wish to use your own connection pooling mechanism,
you can obtain a raw client with #new_client
redis_config = RedisClient.config(host: "10.0.1.1", port: 6380, db: 15)
redis = redis_config.new_client
redis.call("PING") # => "PONG"NOTE: Raw RedisClient instances must not be shared between threads. Make sure to read the section on thread safety.
For simple use cases where only a single connection is needed, you can use the RedisClient.new shortcut:
redis = RedisClient.new
redis.call("GET", "mykey")url: A Redis connection URL, e.g. redis://example.com:6379/5 - a rediss:// scheme enables SSL, and the path is interpreted as a database number.
To connect to UNIX domain sockets, the url can also just be a path, and the database specified as query parameter: /run/redis/foo.sock?db=5, or optionally
have a unix:// scheme: unix:///run/redis/foo.sock?db=5
Note that all other configurations take precedence, e.g. RedisClient.config(url: "redis://localhost:3000", port: 6380) will connect on port 6380.host: The server hostname or IP address. Defaults to "localhost".port: The server port. Defaults to 6379.path: The path to a UNIX socket, if set url, host and port are ignored.ssl: Whether to connect using SSL or not.ssl_params: A configuration Hash passed to OpenSSL::SSL::SSLContext#set_params, notable options include:cert: The path to the client certificate (e.g. client.crt).key: The path to the client key (e.g. client.key).ca_file: The certificate authority to use, useful for self-signed certificates (e.g. ca.crt),db: The database to select after connecting, defaults to 0.id ID for the client connection, assigns name to current connection by sending CLIENT SETNAME.username Username to authenticate against server, defaults to "default".password Password to authenticate against server. Can either be a String or a callable that recieve username as argument and return a passowrd as a String.timeout: The general timeout in seconds, default to 1.0.connect_timeout: The connection timeout, takes precedence over the general timeout when connecting to the server.read_timeout: The read timeout, takes precedence over the general timeout when reading responses from the server.write_timeout: The write timeout, takes precedence over the general timeout when sending commands to the server.idle_timeout: Amount of time after which an idle connection has to be revalidated with a PING command. Defaults to 30 seconds.reconnect_attempts: Specify how many times the client should retry to send queries. Defaults to 0. Makes sure to read the reconnection section before enabling it.circuit_breaker: A Hash with circuit breaker configuration. Defaults to nil. See the circuit breaker section for details.protocol: The version of the RESP protocol to use. Default to 3.custom: A user-owned value ignored by redis-client but available as Config#custom. This can be used to hold middleware configurations and other user-specific metadata.The client is able to perform automatic failover by using Redis Sentinel.
To connect using Sentinel, use:
redis_config = RedisClient.sentinel(
name: "mymaster",
sentinels: [
{ host: "127.0.0.1", port: 26380 },
{ host: "127.0.0.1", port: 26381 },
],
role: :master,
)or:
redis_config = RedisClient.sentinel(
name: "mymaster",
sentinels: [
"redis://127.0.0.1:26380",
"redis://127.0.0.1:26381",
],
role: :master,
)The name identifies a group of Redis instances composed of a master and one or more replicas (mymaster in the example).
It is possible to optionally provide a role. The allowed roles are :master
and :replica. When the role is :replica, the client will try to connect to a
random replica 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 options per instance. 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_config = RedisClient.sentinel(name: 'mymaster', sentinel_username: 'appuser', sentinel_password: 'mysecret', sentinels: SENTINELS, 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_config = RedisClient.sentinel(name: 'mymaster', sentinels: SENTINELS, role: :master, password: 'mysecret')So you have to provide Sentinel credential and Redis explicitly 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_config = RedisClient.sentinel(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_config = RedisClient.sentinel(url: "redis://appuser:mysecret@mymaster/10", sentinels: SENTINELS, role: :master)To horizontally shard keys across multiple servers without relying on clustering, a RedisClient::HashRing class is provided:
ring = RedisClient.ring(
RedisClient.config(host: "10.0.1.1", port: 6380).new_pool(timeout: 0.5, size: 3),
RedisClient.config(host: "10.0.1.2", port: 6380).new_pool(timeout: 0.5, size: 3),
RedisClient.config(host: "10.0.1.3", port: 6380).new_pool(timeout: 0.5, size: 3),
)
ring.node_for("cache_key").call("GET", "cache_key") # => "value"
ring.nodes_for("key1", "key2", "key3").each do |node, keys|
node.call("DEL", *keys)
end
ring.nodes.each do |node|
node.close
endNote that regular clients do respond to node_for, nodes_for and nodes, so that code that support RedisClient.ring is also usable with a single server.
Only a select few Ruby types are supported as arguments beside strings.
Integer and Float are supported:
redis.call("SET", "mykey", 42)
redis.call("SET", "mykey", 1.23)is equivalent to:
redis.call("SET", "mykey", 42.to_s)
redis.call("SET", "mykey", 1.23.to_s)Arrays are flattened as arguments:
redis.call("LPUSH", "list", [1, 2, 3], 4)is equivalent to:
redis.call("LPUSH", "list", "1", "2", "3", "4")Hashes are flattened as well:
redis.call("HMSET", "hash", { "foo" => "1", "bar" => "2" })is equivalent to:
redis.call("HMSET", "hash", "foo", "1", "bar", "2")Any other type requires the caller to explicitly cast the argument as a string.
Keywords arguments are treated as Redis command flags:
redis.call("SET", "mykey", "value", nx: true, ex: 60)
redis.call("SET", "mykey", "value", nx: false, ex: nil)is equivalent to:
redis.call("SET", "mykey", "value", "nx", "ex", "60")
redis.call("SET", "mykey", "value")If flags are built dynamically, you'll have to explicitly pass them as keyword arguments with **:
flags = {}
flags[:nx] = true if something?
redis.call("SET", "mykey", "value", **flags)Important Note: because of the keyword argument semantic change between Ruby 2 and Ruby 3, unclosed hash literals with string keys may be interpreted differently:
redis.call("HMSET", "hash", "foo" => "bar")On Ruby 2 "foo" => "bar" will be passed as a positional argument, but on Ruby 3 it will be interpreted as keyword
arguments. To avoid such problem, make sure to enclose hash literals:
redis.call("HMSET", "hash", { "foo" => "bar" })Contrary to the redis gem, redis-client doesn't do any type casting on the return value of commands.
If you wish to cast the return value, you can pass a block to the #call family of methods:
redis.call("INCR", "counter") # => 1
redis.call("GET", "counter") # => "1"
redis.call("GET", "counter", &:to_i) # => 1
redis.call("EXISTS", "counter") # => 1
redis.call("EXISTS", "counter") { |c| c > 0 } # => true*_v methodsIn some it's more convenient to pass commands as arrays, for that _v versions of call methods are available.
redis.call_v(["MGET"] + keys)
redis.blocking_call_v(1, ["MGET"] + keys)
redis.call_once_v(1, ["MGET"] + keys)For blocking commands such as BRPOP, a custom timeout duration can be passed as first argument of the #blocking_call method:
redis.blocking_call(timeout, "BRPOP", "key", 0)If timeout is reached, #blocking_call raises RedisClient::ReadTimeoutError and doesn't retry regardless of the reconnect_attempts configuration.
timeout is expressed in seconds, you can pass false or 0 to mean no timeout.
For easier use of the SCAN family of commands, #scan, #sscan, #hscan and #zscan methods are provided
redis.scan("MATCH", "pattern:*") do |key|
...
endredis.sscan("myset", "MATCH", "pattern:*") do |key|
...
endFor HSCAN and ZSCAN, pairs are yielded
redis.hscan("myhash", "MATCH", "pattern:*") do |key, value|
...
endredis.zscan("myzset") do |element, score|
...
endIn all cases the cursor parameter must be omitted and starts at 0.
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
No open issues yet, or sync has not completed.