首页
/ Redis-rb 项目技术文档

Redis-rb 项目技术文档

2024-12-23 13:22:44作者:何将鹤

1. 安装指南

1.1 安装 Ruby 客户端

要安装 redis-rb 客户端,请在终端中运行以下命令:

$ gem install redis

1.2 验证安装

安装完成后,可以通过以下命令验证是否安装成功:

require "redis"
redis = Redis.new
redis.ping

如果返回 "PONG",则表示安装成功。

2. 项目的使用说明

2.1 连接到 Redis

默认情况下,redis-rb 客户端会连接到本地 Redis 实例(localhost:6379)。你可以通过以下方式连接到 Redis:

require "redis"

redis = Redis.new

如果需要连接到远程服务器或使用非默认端口,可以使用以下方式:

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

2.2 使用 URL 连接

你也可以使用 redis:// URL 格式来指定连接选项:

redis = Redis.new(url: "redis://:p4ssw0rd@10.0.1.1:6380/15")

2.3 连接到 Unix 套接字

如果 Redis 监听 Unix 套接字,可以使用以下方式连接:

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

2.4 连接到需要密码的 Redis 实例

如果 Redis 实例需要密码,可以使用以下方式连接:

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

2.5 使用 ACL 连接

如果 Redis 实例启用了 ACL,可以使用以下方式连接:

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

3. 项目API使用文档

3.1 基本命令

redis-rb 客户端的方法名称与 Redis 命令一一对应。例如,SETGET 命令可以这样调用:

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

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

3.2 连接池

redis-rb 客户端不提供连接池功能,但建议使用 connection_pool gem 来实现连接池:

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

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

3.3 Sentinel 支持

redis-rb 支持通过 Redis 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)

3.4 集群支持

redis-rb 通过 redis-clustering gem 支持 Redis 集群。

3.5 管道操作

你可以使用管道来批量执行多个命令:

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

3.6 事务操作

你可以使用 MULTI/EXEC 来执行原子操作:

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

4. 项目安装方式

4.1 通过 Gem 安装

最简单的安装方式是通过 RubyGems 安装:

$ gem install redis

4.2 手动安装

你也可以从 GitHub 下载源码并手动安装:

$ git clone https://github.com/redis/redis-rb.git
$ cd redis-rb
$ gem build redis.gemspec
$ gem install redis-*.gem

通过以上步骤,你可以成功安装并使用 redis-rb 客户端。

登录后查看全文
热门项目推荐
相关项目推荐