LuaRestyLock
优质
小牛编辑
141浏览
2023-12-01
lua-resty-lock 是什么?
lua-resty-lock 是一个基于 Nginx 共享内存(ngx.shared.DICT)的非阻塞锁(基于 Nginx 的时间事件实现),说它是非阻塞的是因为它不会阻塞 Nginx 的 worker 进程,当某个key(请求)获取到该锁后,后续试图对该 key 再一次获取锁时都会『阻塞』在这里,但不会阻塞其它的 key。当第一个获取锁的 key 将获取到的数据更新到缓存后,后续的 key 就不会再回源后端应用了,从而可以起到保护后端应用的作用。
lua-resty-lock 是干什么的呢?
它是解决缓存失效风暴的利器。缓存失效风暴是指缓存因为时间过期而失效时,会导致所有的请求都去访问 后台的 redis 或者 mysql,而导致 CPU 性能即刻增长的现象。所以关键是当缓存失效时,用 lock 保证只有一个线程去访问后台的 redis 或者 mysql,然后更新缓存。需要使用到 lua-resty-lock 模块的加锁、解锁功能。
lua-resty-lock 怎么应用呢?
这是 lua-resty-lock 官方文档:https://github.com/openresty/lua-resty-lock
这里假设我们使用 ngx_lua 共享内存字典来缓存 Redis 查询结果,我们在使用中有如下配置 nginx.conf
:
设置 10m 的缓存空间和 1m 存储锁的空间
# you may want to change the dictionary size for your cases.
lua_shared_dict my_cache 10m;
lua_shared_dict my_locks 1m;
- 从本地缓存 my_cache 中获取数据;
- 若果存在值直接返回,如果缓存中不存在值就获取 resty_lock 锁;
- 再次检查缓存是否有值,因为可能有人把值放入到缓存中;
- 如果还是没有获取到数据,就从 redis 集群中获取数据.。如果 rereis 中也没有获取到数据,就会回溯到服务器获取数据;
- 更新分布式缓存 redis,再更新本地缓存 my_cache。
local resty_lock = require "resty.lock"
local cache = ngx.shared.my_cache
-- step 1:
local val, err = cache:get(key)
if val then
ngx.say("result: ", val)
return
end
if err then
return fail("failed to get key from shm: ", err)
end
-- cache miss!
-- step 2:
local lock, err = resty_lock:new("my_locks")
if not lock then
return fail("failed to create lock: ", err)
end
local elapsed, err = lock:lock(key)
if not elapsed then
return fail("failed to acquire the lock: ", err)
end
-- lock successfully acquired!
-- step 3:
-- someone might have already put the value into the cache
-- so we check it here again:
val, err = cache:get(key)
if val then
local ok, err = lock:unlock()
if not ok then
return fail("failed to unlock: ", err)
end
ngx.say("result: ", val)
return
end --- step 4:
local val = fetch_redis(key)
if not val then
local ok, err = lock:unlock()
if not ok then
return fail("failed to unlock: ", err)
end
-- get data from backend
local val = get_from_backend(key)
ngx.say("result: ", val)
local ok,err = update_redis(val);
if not ok then
return fail("failed to upadte redis: ", err)
end
end
-- update the shm cache with the newly fetched value
local ok, err = cache:set(key, val, 1)
if not ok then
local ok, err = lock:unlock()
if not ok then
return fail("failed to unlock: ", err)
end
return fail("failed to update shm cache: ", err)
end
local ok, err = lock:unlock()
if not ok then
return fail("failed to unlock: ", err)
end
ngx.say("result: ", val)