我是 redis 的新手。我有一个 CMS,它以这样的结构将 JSON 输出到 redis:
partial:1 => {id: 1, title: 'Foo1', ...}
partial:2 => {id: 2, title: 'Foo2', ...}
partial:3 => {id: 3, title: 'Foo3', ...}
page:home => {
id: 'Homepage',
teaser1: 'partial:1',
teaser2: 'partial:2',
teaser3: {type: Slider, content: 'partial:3'}
}
因此 JSON 可以在其结构中包含符合特定命名方案的其他 redis-keys。我想要的是一种查询 redis 的方法,这样当我得到 page:home
-key 时,对 json 中其他键的引用得到“扩展”到它们各自的值,如下所示:
{
id: 'Homepage',
teaser1: {id: 1, title: 'Foo1', ...},
teaser2: {id: 2, title: 'Foo2', ...},
teaser3: {type: Slider, content: {id: 3, title: 'Foo3', ...}
}
这可能吗?如何实现?
最佳答案
是的。这是很有可能。这是一种工作方法:
创建一个函数将您的 redis 哈希(例如:partial:*,page:home)转换为 lua 表:hgetall
<创建一个函数来检查给定的 redis 哈希名是否符合您的命名方案,如果符合则使用 hgetall 将其转换为 lua 表;否则返回相同的值:evaluate_hash
- 创建一个函数来评估和转换给定哈希名称的所有属性并将其作为 json 返回:expand
这是一个简单的实现:
--脚本:redis_expand_as_json.lua
--Function to Convert a given hash name (e.g: partial:1..n, page:home) to a lua table
local function hgetall(a)local b=redis.call('HGETALL',a)local c={}local d;for e,f in ipairs(b)do if e%2==1 then d=f else c[d]=f end end;return c end
--Function to check if the given value conforms with a naming scheme,
-- if so convert it to a lua table; otherwise return the values as is.
local function evaluate_hash(value)
local pattern = "partial:%d+"
if string.match(value, pattern) then
return hgetall(value)
else
return value
end
end
--Function to convert a given hash_name to a lua table,
-- iterate all elements and convert them to lua table if necessary
-- returns the table as a json object
local function expand(hash_name)
local obj_table = hgetall(hash_name)
for k, val in pairs(obj_table) do
obj_table[k] = evaluate_hash(val)
end
return cjson.encode(obj_table)
end
local page = KEYS[1]
local json_result = expand(page) or {}
redis.log(redis.LOG_NOTICE, tostring(json_result))
return json_result
在控制台中测试:
redis-cli -c hmset "partial:1" id 1 title foo1
好的
redis-cli -c hmset "partial:2" id 2 title foo2
好的
redis-cli -c hmset 'page:home' id 'Homepage' teaser1 'partial:1' teaser2 'partial:2'
好的
redis-cli EVAL "$(cat redis_expand_as_json.lua)" 1 'page:home'
{"teaser1":{"id":"1","title":"foo1"},"teaser2":{"id":"2","title":"foo2"},"id":"Homepage"}
关于lua - Redis:将值中的关键引用扩展到它们的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26860724/