欢迎来到我的博客园

Redis redis key的介绍

Redis key的含义

redis 的key 是在redis中非常重要的角色,通常我们提到key-value, key在redis中一般是字符串类型,value通常有5中不同的类型,例如 strings, set ,list,sorted set ,hashes。

在redis中我们对数据进行操作时,通常是对key来进行操作。只有设置了key,我们才能对key进行相应的复值,修改,删除等操作。

Redis keys设置的规则

Redis key值是二进制安全的,这意味着可以用任何二进制序列作为key值,从形如”foo”的简单字符串到一个JPEG文件的内容都可以。空字符串也是有效key值。

关于key的几条规则:

  • 太长的键值不是个好主意,例如1024字节的键值就不是个好主意,不仅因为消耗内存,而且在数据中查找这类键值的计算成本很高。
  • 太短的键值通常也不是好主意,如果你要用”u:1000:pwd”来代替”user:1000:password”,这没有什么问题,但后者更易阅读,并且由此增加的空间消耗相对于key object和value object本身来说很小。当然,没人阻止您一定要用更短的键值节省一丁点儿空间。
  • 最好坚持一种模式。例如:”object-type:id:field”就是个不错的注意,像这样”user:1000:password”。我喜欢对多单词的字段名中加上一个点,就像这样:”comment:1234:reply.to”。

 

Redis key相关的常用命令

keys命令

keys命令,返回所有符合匹配模式的的key的列表:

注意:在生产库中我们一定要避免使用keys *这个命令。如果数据库很大,这个命令可能对性能有很大的影响,如果想找某个key,请考虑使用scan或sets命令

Supported glob-style patterns:

h?llo     匹配hello, hallo and hxllo
h*llo     匹配 hllo and heeeello
h[ae]llo  匹配hello and hallo, but not hillo
h[^e]llo  匹配hallo, hbllo, ... but not hello
h[a-b]llo 匹配hallo and hbllo
redis:6379> MSET firstname Jack lastname Stuntman age 35
"OK"
redis:6379> KEYS *name*
1) "firstname"
2) "lastname"
redis:6379> KEYS a??
1) "age"
redis:6379> KEYS *
1) "firstname"
2) "lastname"
3) "age"
redis:6379> 

type命令

type命令查询key对应的的值的类型。

127.0.0.1:6379> help type

  TYPE key
  summary: Determine the type stored at key
  since: 1.0.0
  group: generic
127.0.0.1:6379> type key1
string

exists命令

exists命令判断 键是否存在当前数据库中。如果存在返回1 ,如果不存在返回0。

127.0.0.1:6379> help exists

  EXISTS key [key ...]
  summary: Determine if a key exists
  since: 1.0.0
  group: generic
127.0.0.1:6379> exists name
(integer) 1
127.0.0.1:6379> exists name2
(integer) 0

randomkey 命令

randomkey命令会随机返回一个key的名字

127.0.0.1:6379> help randomkey

  RANDOMKEY -
  summary: Return a random key from the keyspace
  since: 1.0.0
  group: generic

127.0.0.1:6379> randomkey
"k1"
127.0.0.1:6379> randomkey
"counter:__rand_int__"
127.0.0.1:6379> randomkey
"myhash"

rename命令 

rename命令将 key修改名字为另外一个key。

127.0.0.1:6379> rename name name2
OK
127.0.0.1:6379> exists name2
(integer) 1

127.0.0.1:6379> exists name
(integer) 0

127.0.0.1:6379> get name2
"1"

touch 命令

修改key的最后访问时间

127.0.0.1:6379> help touch

  TOUCH key [key ...]
  summary: Alters the last access time of a key(s). Returns the number of existing keys specified.
  since: 3.2.1
  group: generic

127.0.0.1:6379> object idletime name2
(integer) 6
127.0.0.1:6379> touch name2
(integer) 1
127.0.0.1:6379> object idletime name2
(integer) 2

copy命令

copy命令将一个键的值拷贝到另一个键中,可以指定数据库,也可以指定是否替换已存在的键,返回值1表示拷贝成功,返回值0表示拷贝失败。

127.0.0.1:6379> help copy

  COPY source destination [DB destination-db] [REPLACE]
  summary: Copy a key
  since: 6.2.0
  group: generic

127.0.0.1:6379> copy name2 name
(integer) 1
127.0.0.1:6379> get name
"test"
127.0.0.1:6379> get name2
"test"
127.0.0.1:6379> copy name2 name
(integer) 0
127.0.0.1:6379> copy name2 name replace
(integer) 1

 

posted @ 2022-07-31 23:15  panzq  阅读(5011)  评论(0编辑  收藏  举报