Redis是一个高性能、内存型的键值存储系统,不仅作为数据库和缓存使用,还可作为消息中间件。其提供了丰富的数据结构支持,如字符串、列表、集合、哈希表以及有序集合等,并具有事务处理、持久化及发布/订阅等多种高级特性。以下对Redis中关键命令进行详细解释并举例:
连接Redis服务器
redis-cli
以连接本地或远程服务器,默认端口为6379。redis-cli -h hostname -p port_number
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
选择数据库
SELECT index
:切换到指定索引号的数据库(0-15)。SELECT 0
键值对操作
设置键值:SET key value [EX seconds] [PX milliseconds] [NX|XX]
SET mykey "Hello World" EX 60 PX 3000 NX
获取键值:GET key
GET mykey
删除键:DEL key [key ...]
DEL mykey anotherKey
设置/更新值:SET key value
SET user:1:name "Alice"
原子自增/自减:INCR key
或 DECR key
INCR counter
DECR visits:today
获取长度:STRLEN key
STRLEN user:1:name
获取子串:GETRANGE key start end
GETRANGE message 0 3
头部插入元素:LPUSH key value [value ...]
LPUSH shopping_list bread milk eggs
尾部插入元素:RPUSH key value [value ...]
RPUSH inbox new_message
弹出并获取元素:
LPOP key
LPOP shopping_list
RPOP key
RPOP inbox
查询列表内容:LRANGE key start stop
LRANGE shopping_list 0 -1
添加成员:SADD key member [member ...]
SADD users:online 1 2 3
移除成员:SREM key member [member ...]
SREM users:online 3
查询成员状态:SISMEMBER key member
SISMEMBER users:online 1
计算集合操作:
SDIFF key1 key2
SUNION key1 key2
SDIFF key1 key2
SUNION setA setB
插入哈希字段:HSET key field value
HSET user:1 username Alice
读取哈希字段:HGET key field
HGET user:1 username
获取整个哈希表:HGETALL key
HGETALL user:1
按分数添加成员:ZADD key score member [score member ...]
ZADD leaderboard 100 player1 200 player2
范围查询:ZRANGE key start stop [WITHSCORES]
ZRANGE leaderboard 0 -1 WITHSCORES
删除成员:ZREM key member [member ...]
ZREM leaderboard player1
事务处理
MULTI
MULTI
EXEC
SET transaction_key value
INCR transaction_counter
EXEC
DISCARD
WATCH key [key ...]
持久化
BGSAVE
config set appendonly yes
。发布/订阅
PUBLISH channel message
PUBLISH news "Breaking News!"
SUBSCRIBE channel [channel ...]
SUBSCRIBE news weather
UNSUBSCRIBE [channel ...]
以上仅介绍了Redis常用功能的一小部分,实际应用中可以灵活运用各种命令和数据结构来满足复杂场景的需求。