Redis Cheat Sheet

Redis 是一个开源的键值数据库。redis-cli 是 Redis 的命令行界面,用于与 Redis 服务器交互。

Install

Installing Redis

Update your local apt package cache:

sudo apt update

Then install Redis by apt:

sudo apt install redis-server

Configuring Redis

sudo vim /etc/redis/redis.conf

Inside the file, find the supervised directive. This directive allows you to declare an init system to manage Redis as a service, providing you with more control over its operation. The supervised directive is set to no by default.

Since you are running Ubuntu, which uses the systemd init system, change this to systemd:

/etc/redis/redis.conf
# If you run Redis from upstart or systemd, Redis can interact with your
# supervision tree. Options:
#   supervised no      - no supervision interaction
#   supervised upstart - signal upstart by putting Redis into SIGSTOP mode
#   supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET
#   supervised auto    - detect upstart or systemd method based on
#                        UPSTART_JOB or NOTIFY_SOCKET environment variables
# Note: these supervision methods only signal "process is ready."
#       They do not enable continuous liveness pings back to your supervisor.
supervised systemd

Then, restart the Redis service to reflect the changes you made to the configuration file:

sudo systemctl restart redis.service

Binding to localhost

By default, Redis is only accessible from localhost.

Redis CLI

连接和认证

  • redis-cli:连接到本地运行的 Redis 服务器。
  • redis-cli -h <hostname> -p <port>:连接到指定主机和端口的 Redis 服务器。
  • AUTH <password>:使用密码认证。

键(Keys)操作

  • KEYS <pattern>:查找所有匹配给定模式的键。
  • EXISTS <key>:检查键是否存在。
  • DEL <key>:删除键。
  • EXPIRE <key> <seconds>:设置键的过期时间。
  • TTL <key>:查询键的剩余生存时间(TTL, time to live)。
  • FLUSHDB:删除当前数据库的所有键。
  • FLUSHALL:删除所有数据库的所有键。

字符串(String)操作

  • SET <key> <value>:设置字符串值。
  • GET <key>:获取字符串值。
  • INCR <key>:将键的整数值增加 1。
  • DECR <key>:将键的整数值减少 1。

列表(List)操作

  • LPUSH <key> <value>:将一个值插入到列表头部。
  • RPUSH <key> <value>:将一个值插入到列表尾部。
  • LPOP <key>:移出并获取列表的第一个元素。
  • RPOP <key>:移出并获取列表的最后一个元素。
  • LRANGE <key> <start> <stop>:获取列表指定范围内的元素。

集合(Set)操作

  • SADD <key> <member>:向集合添加一个成员。
  • SMEMBERS <key>:获取集合的所有成员。
  • SREM <key> <member>:移除集合中的一个成员。
  • SISMEMBER <key> <member>:判断成员元素是否是集合的成员。

散列(Hash)操作

  • HSET <key> <field> <value>:设置散列字段的字符串值。
  • HGET <key> <field>:获取存储在散列中的值。
  • HDEL <key> <field>:删除散列的一个字段。
  • HKEYS <key>:获取散列中的所有字段名。

有序集合(Sorted Set)操作

  • ZADD <key> <score> <member>:向有序集合添加一个成员。
  • ZRANGE <key> <start> <stop> [WITHSCORES]:按照索引区间返回有序集合指定区间内的成员。
  • ZREM <key> <member>:移除有序集合中的一个成员。

事务

  • MULTI:标记一个事务块的开始。
  • EXEC:执行所有事务块内的命令。

发布/订阅

  • SUBSCRIBE <channel>:订阅给定的一个或多个频道。
  • PUBLISH <channel> <message>:将信息发送到指定的频道。

其他命令

  • PING:测试连接是否存活。
  • INFO:获取服务器的信息和统计。
  • CONFIG GET <pattern>:获取 Redis 配置参数。
  • CONFIG SET <parameter> <value>:设置 Redis 配置参数。
  • SAVE:同步地保存数据到硬盘。
  • BGSAVE:异步地保存数据到硬盘。