与其将客户存储为字符串,不如将它们存储为哈希值。Redis 的哈希 ziplist 编码非常节省空间。如果你存储超过 70 个元素,你应该考虑hash-max-ziplist-entries
在你的 redis.conf 中提高限制
SORT
当您使用 Redis 哈希时,您可以做一些有趣的事情。通过使用SORT
with GET
,STORE
您可以从客户那里获取所有城市并将它们存储为列表(不区分)。然后,您可以通过调用lpop
和sadd
覆盖列表将列表转换为集合。
这是一个示例 Redis Lua 脚本:
-- a key which holds a set of customer keys
local set_of_customer_keys = KEYS[1]
-- a maybe-existing key which will hold the set of cities
local distinct_set = ARGV[1]
-- attribute to get (defaults to city)
local attribute = ARGV[2] or 'city'
-- remove current set of distinct_cities
redis.call("DEL", distinct_set)
-- use SORT to build a list out of customer hash values for `attribute`
local cities = redis.call("SORT", set_of_customer_keys, "BY", "nosort", "GET", "*->"..attribute)
-- loop through all cities in the list and add them to the distinct cities set
for i, city in pairs(cities) do
redis.call("SADD", distinct_set, city)
end
-- return the distinct cities
return redis.call("SMEMBERS", distinct_set)
您还可以保留一customer__100000__cities
组与客户的属性一起永久存储并用于sinter *customer_cities_keys
获取一组不同的城市,但这会降低内存效率。