0

Redis键管理

 2 years ago
source link: https://maoqiankun97.github.io/posts/redis/redis%E9%94%AE%E7%AE%A1%E7%90%86/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Redis键管理

1. 单个键管理

1.1 键重命名

rename key newkey

1.2 随机返回一个键

randomkey

1.3 键过期

expire key seconds (键在seconds秒后过期) expireat key timestamp (键在秒级时间戳timestamp后过期) pexpire key milliseconds (键在milliseconds毫秒后过期) pexpireat key milliseconds-timestamp (键在毫秒级时间戳后过期)

persist key (清除键过期时间)

  • 对于字符串类型键,执行set命令会去掉过期时间
  • redis不支持二级数据结构内部元素的过期功能,例如不能对列表类型的一个元素做过期时间设置
  • setex是set+expire的原子组合

1.4 迁移键

1.4.1 move key db

1.4.2 dump + restore

dump key restore key ttl value (ttl为毫秒级的过期时间, ttl为0时代表永不过期)

1.4.3 migrate

migrate host port key|"" destination-db timeout [COPY] [REPLACE] [keys key [key …]] host: 目标redis的ip地址 port: 目标redis的端口 key|"": 需要迁移多个键的时候为空字符串,否则为要迁移的键 destination-db: 目标redis的数据库索引 timeout: 毫秒级的过期时间 [copy]: 添加此选项以后,迁移后不删除源键 [replace]: 添加此选项以后不管目标redis是否存在该键都会正常进行数据覆盖 [keys key [key …]]: 迁移多个键时,在此处填写,如 keys key1 key2

2. 遍历键

2.1 全量遍历键

keys pattern

pattern规则:

  • * 代表匹配任意字符
  • ? 代表匹配一个字符
  • [] 代表匹配部分字符,如[1,3]代表匹配1或者3,[1-10]代表匹配1到10的任意数字
  • \x 用来做转义,如要匹配*,?需要进行转义: \*、\?

2.2 渐进式遍历

scan cursor [match pattern] [count number]

  • cursor 是一个必需参数,实际上cursor是一个游标,第一次遍历从0开hi,每次scan遍历完都会返回当前游标的值,直至游标值为0表示遍历结束。在redis种key可视为存在一个一维数组之中,如果redis中有三个key,遍历顺序为 0b00->0b10->0b01,采用这种遍历顺序的好处是如果在遍历中redis的key数组发生了扩容,如原有的 0b00、0b10、0b01、0b11四个游标扩容为0b000、0b100、0b010、0b110、0b001、0b101、0b011、0b111八个游标,此时如果在扩容前scan遍历至0b10这个游标,此时只需要从0b010开始遍历。
  • match pattern 是可选参数,即匹配的模式
  • count number 是可选参数,表示此次遍历需要遍历的键个数,默认为10
  • 除scan以外,Redis提供了面向hash类型、set类型、sorted-set类型的扫描遍历命令,分别是hscan、sscan、zscan,用法基本类似。

3. 数据库管理

3.1 切换数据库

select dbIndex

3.2 flushdb

清空当前数据库

3.3 flushall

清空所有数据库


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK