根据Tokyo Tyrant自带的Lua队列脚本修改,Kyoto Cabinet和Tokyo Tyrant的API有很大不同。
kt = __kyototycoon__
db = kt.db
-- 记录日志
if kt.thid == 0 then
kt.log("system", "the Lua script has been loaded")
end
-- 入队列
function enqueue(inmap, outmap)
local key = inmap.key
local value = inmap.value
--队列值自增1,空从0开始
local id = db:increment_double(key, 1)
if not id then
return kt.RVEINTERNAL
end
key = string.format("%s-%012d", key, id)
if not db:add(key, value) then
return kt.RVEINTERNAL
end
outmap[key] = "ok"
return kt.RVSUCCESS
end
-- 出队列
function dequeue(inmap, outmap)
local key = inmap.key
local max = inmap.max
max = tonumber(max)
if not max or max < 1 then
max = 1
end
key = string.format("%s-", key)
--匹配队列前缀,返回多个匹配的key
local keys = db:match_prefix(key, max)
local res = ""
for i = 1, #keys do
local key = keys[i]
local value = db:get(key)
if db:remove(key) and value then
--要返回的结果
outmap[keys[i]] = value
end
end
return kt.RVSUCCESS
end
-- 查看队列大小
function queuesize(inmap, outmap)
local key = inmap.key
key = string.format("%s-", key)
local keys = db:match_prefix(key)
outmap.size = #keys
return kt.RVSUCCESS
end
-- 重置队列ID从0开始
function queuereset(inmap, outmap)
local key = inmap.key
if not key then
return kt.RVEINVALID
end
if not db:remove(key) then
local err = db:error()
if err:code() == kt.Error.NOREC then
return kt.RVELOGIC
end
return kt.RVEINTERNAL
end
return kt.RVSUCCESS
end
使用:
ktremotemgr script -host 192.168.1.3 -port 1978 enqueue key queue value value1
ktremotemgr script -host 192.168.1.3 -port 1978 dequeue key queue max 10
curl "http://192.168.1.3:1978/rpc/play_script?name=enqueue&_key=queue&_value=value1"
curl "http://192.168.1.3:1978/rpc/play_script?name=dequeue&_key=queue&_max=10"