Skip to content

Instantly share code, notes, and snippets.

@findstr
Created November 4, 2020 06:11
Show Gist options
  • Save findstr/cc456e9394390d89a787f66176b3397a to your computer and use it in GitHub Desktop.
Save findstr/cc456e9394390d89a787f66176b3397a to your computer and use it in GitHub Desktop.
command cache for redis
local M = {}
local pairs = pairs
local length = 0
local seq = {}
local map = {}
local marshal = function(v, schema)
return v.hello .. ":" .. v.world
end
local function overwrite(v, t)
local i = length + 1
local k = map[v]
if k then
print("clear", k)
seq[k] = nil
end
length = i
map[v] = length
seq[length] = t
end
function M.hset(dbk, k, v, schema)
local t = {"hset", dbk, k, v, schema}
overwrite(v, t)
end
function M.hdel(dbk, k)
length = length + 1
seq[length] = {"hdel", dbk, k}
end
function M.set(dbk, v, schema)
local t = {"set", dbk, v, schema}
overwrite(v, t)
end
function M.del(dbk)
length = length + 1
seq[length] = {"del", dbk}
end
function M.flush()
if length == 0 then
return
end
for k, _ in pairs(map) do
map[k] = nil
end
local j = 0
local pipeline = seq
for i = 1, length do
local cmd
cmd = seq[i]
if cmd then
local op = cmd[1]
if op == "set" or op == "hset" then
local n = #cmd
local dat = marshal(cmd[n-1], cmd[n])
cmd[n] = nil
cmd[n-1] = dat
end
j = j + 1
seq[j] = cmd
end
end
for i = j+1, length do
seq[i] = nil
end
length = 0
seq = {}
return pipeline
end
do
local json = require "json"
local obj1 = {hello = "hello", world = "world"}
local obj2 = {hello = "hello2", world = "world2"}
local obj3 = {hello = "hello3", world = "world3"}
local obj4 = {hello = "hello4", world = "world4"}
local obj5 = {hello = "hello5", world = "world5"}
M.set("foo", obj1, "pfoo")
M.hset("bar", 1, obj2, "pbar")
M.hset("bar", 1, obj2, "pbar")
M.set("foo", obj1, "pfoo")
M.hdel("bar", 1)
M.del("foo")
M.set("foo", obj3, "pfoo")
M.hset("bar", 1, obj4, "pbar")
M.hset("bar", 2, obj5, "pbar")
print(json.encode(M.flush()))
end
return M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment