Redis使用:聚合类型为空时,会自动被Redis删除

Posted 程序员的自我修养

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Redis使用:聚合类型为空时,会自动被Redis删除相关的知识,希望对你有一定的参考价值。

项目中使用Redis来记录用户的上线和下线信息,其中用到了集合(sets)类型,某用户上线时,向sets中添加数据,下线时将相应数据从sets中删除,考虑当该用户的所有实例都下线时,需要将sets删除。

因为是并发操作,就考虑到判断为空后进行删除操作的原子性,查了一堆资料,都已经写好了相应的lua脚本(因为Redis执行lua脚本能保证原子性):

    if redis.call(scard,KEYS[1]) == 0
    then
        return redis.call(del,KEYS[1])
    else
        return 0
    end

 

结果后来发现Redis中已经自动实现了该功能,也就是所有聚合类型:lists,sets, Sorted Sets 和 Hashes,当为空时,都会被自动删除!

服!!!

Automatic creation and removal of keys

So far in our examples we never had to create empty lists before pushing elements, or removing empty lists when they no longer have elements inside. It is Redis‘ responsibility to delete keys when lists are left empty, or to create an empty list if the key does not exist and we are trying to add elements to it, for example, with LPUSH.

This is not specific to lists, it applies to all the Redis data types composed of multiple elements -- Sets, Sorted Sets and Hashes.

Basically we can summarize the behavior with three rules:

  1. When we add an element to an aggregate data type, if the target key does not exist, an empty aggregate data type is created before adding the element.
  2. When we remove elements from an aggregate data type, if the value remains empty, the key is automatically destroyed.
  3. Calling a read-only command such as LLEN (which returns the length of the list), or a write command removing elements, with an empty key, always produces the same result as if the key is holding an empty aggregate type of the type the command expects to find.

Examples of rule 1:

> del mylist
(integer) 1
> lpush mylist 1 2 3
(integer) 3

However we can‘t perform operations against the wrong type if the key exists:

> set foo bar
OK
> lpush foo 1 2 3
(error) WRONGTYPE Operation against a key holding the wrong kind of value
> type foo
string

Example of rule 2:

> lpush mylist 1 2 3
(integer) 3
> exists mylist
(integer) 1
> lpop mylist
"3"
> lpop mylist
"2"
> lpop mylist
"1"
> exists mylist
(integer) 0

The key no longer exists after all the elements are popped.

Example of rule 3:

> del mylist
(integer) 0
> llen mylist
(integer) 0
> lpop mylist
(nil)


https://redis.io/topics/data-types-intro




以上是关于Redis使用:聚合类型为空时,会自动被Redis删除的主要内容,如果未能解决你的问题,请参考以下文章

当聚合函数为空时,Sequelize 获取结果

在聚合管道中过滤数组为空时保留主文档

将html页面转换为string类型保存到redis中

spring boot加mybatis使用Map返回时,当值为空时属性也会没有(转)

C++验证redis返回的数据是不是为空

Redis基础操作学习