百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
R

redis-client

> 编程语言
开源

用于 Redis 6+ 的简单低级客户端

159 stars0 点赞3 次浏览
访问官网GitHub

工具介绍

用于 Redis 6+ 的简单低级客户端

RedisClient

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.

Installation

Add this line to your application's Gemfile:

ruby
gem 'redis-client'

And then execute:

$ bundle install

Or install it yourself as:

$ gem install redis-client

Usage

To use RedisClient you first define a connection configuration, from which you can create a connection pool:

ruby
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:

ruby
redis.with do |r|
  r.call("SET", "mykey", "hello world") # => "OK"
  r.call("GET", "mykey") # => "hello world"
end

If 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

ruby
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:

ruby
redis = RedisClient.new
redis.call("GET", "mykey")

Configuration

  • 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.

Sentinel support

The client is able to perform automatic failover by using Redis Sentinel.

To connect using Sentinel, use:

ruby
redis_config = RedisClient.sentinel(
  name: "mymaster",
  sentinels: [
    { host: "127.0.0.1", port: 26380 },
    { host: "127.0.0.1", port: 26381 },
  ],
  role: :master,
)

or:

ruby
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.

ruby
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

ruby

# 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

ruby
# 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:

ruby
redis_config = RedisClient.sentinel(url: "redis://appuser:mysecret@mymaster/10", sentinels: SENTINELS, role: :master)

Consistent Hashing

To horizontally shard keys across multiple servers without relying on clustering, a RedisClient::HashRing class is provided:

ruby
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
end

Note 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.

Type support

Only a select few Ruby types are supported as arguments beside strings.

Integer and Float are supported:

ruby
redis.call("SET", "mykey", 42)
redis.call("SET", "mykey", 1.23)

is equivalent to:

ruby
redis.call("SET", "mykey", 42.to_s)
redis.call("SET", "mykey", 1.23.to_s)

Arrays are flattened as arguments:

ruby
redis.call("LPUSH", "list", [1, 2, 3], 4)

is equivalent to:

ruby
redis.call("LPUSH", "list", "1", "2", "3", "4")

Hashes are flattened as well:

ruby
redis.call("HMSET", "hash", { "foo" => "1", "bar" => "2" })

is equivalent to:

ruby
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:

ruby
redis.call("SET", "mykey", "value", nx: true, ex: 60)
redis.call("SET", "mykey", "value", nx: false, ex: nil)

is equivalent to:

ruby
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 **:

ruby
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:

ruby
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:

ruby
redis.call("HMSET", "hash", { "foo" => "bar" })

Commands return values

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:

ruby
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 methods

In some it's more convenient to pass commands as arrays, for that _v versions of call methods are available.

ruby
redis.call_v(["MGET"] + keys)
redis.blocking_call_v(1, ["MGET"] + keys)
redis.call_once_v(1, ["MGET"] + keys)

Blocking commands

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.

Scan commands

For easier use of the SCAN family of commands, #scan, #sscan, #hscan and #zscan methods are provided

ruby
redis.scan("MATCH", "pattern:*") do |key|
  ...
end
ruby
redis.sscan("myset", "MATCH", "pattern:*") do |key|
  ...
end

For HSCAN and ZSCAN, pairs are yielded

ruby
redis.hscan("myhash", "MATCH", "pattern:*") do |key, value|
  ...
end
ruby
redis.zscan("myzset") do |element, score|
  ...
end

In all cases the cursor parameter must be omitted and starts at 0.

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

Issues· 9 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言