项目中使用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:
- 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.
- When we remove elements from an aggregate data type, if the value remains empty, the key is automatically destroyed.
- 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