• 周四. 12月 1st, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Redis server uses Lua’s if modified since caching mode – r4um

[db:作者]

1月 6, 2022

Retrieve data from the cache using if modified since Type can save a lot of network bandwidth and computing time . The data modification time reference should come from the client , And send as part of the request , Instead of the method based on the unacknowledged type, assume that on the server side , Just like the last time the client connected to the server . This model can be used in Redis On the server side of  lua on redis, Implementation costs very little in terms of latency .

We can put a key The last modification time of is stored in a In the hash , And the value is retrieved only if it is more recent than the time sent by the client .

following Lua The fragment is named MY_KEYSTIME The modification time of the key in the hash is stored / retrieval .

According to the modification time

local keys_mtime_hset = "MY_KEYSMTIME"
local key = KEYS[1]
local mtime = tonumber(ARGV[1])
local key_mtime = redis.call('HGET', keys_mtime_hset, key)
key_mtime = tonumber(key_mtime)
-- if missing key in the hash set return the value of the key.
-- or key mtime > mtime 
if not key_mtime or key_mtime > mtime then
    return redis.call('GET', key)
end
return nil 

Set and update modification times :

local keys_mtime_hset = "MY_KEYSMTIME"
local key = KEYS[1]
local value = ARGV[1]
local mtime = tonumber(ARGV[2])
redis.call('SET', key, value)
redis.call('HSET', keys_mtime_hset, key, mtime)

The client is retrieving and setting key Send modification time when .Redis Lua The script is Atomic .

following python The code illustrates a complete working example .

mtime_get=""" local keys_mtime_hset = "MY_KEYSMTIME" local key = KEYS[1] local mtime = tonumber(ARGV[1]) local key_mtime = redis.call('HGET', keys_mtime_hset, key) key_mtime = tonumber(key_mtime) -- if missing key in the hash set return the value of the key. -- or key mtime > mtime if not key_mtime or key_mtime > mtime then return redis.call('GET', key) end return nil """
mtime_set=""" local keys_mtime_hset = "MY_KEYSMTIME" local key = KEYS[1] local value = ARGV[1] local mtime = tonumber(ARGV[2]) redis.call('SET', key, value) redis.call('HSET', keys_mtime_hset, key, mtime) """
m1 = int(time.time())
r = redis.Redis(host='localhost', port=6379)
MTGET=r.register_script(mtime_get)
MTSET=r.register_script(mtime_set)
t_k = "Hello"
t_v = "World"
r.delete(t_k)
print(MTGET(keys=[t_k], args=[m1]))
print(MTSET(keys=[t_k], args=[t_v, m1]))
print(r.get(t_k))
print(MTGET(keys=[t_k], args=[m1 - 100]))
print(MTGET(keys=[t_k], args=[m1 + 100]))

function :

None
None
b'World'
b'World'
None

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注