在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):openresty/lua-resty-lock开源软件地址(OpenSource Url):https://github.com/openresty/lua-resty-lock开源编程语言(OpenSource Language):Lua 91.8%开源软件介绍(OpenSource Introduction):Namelua-resty-lock - Simple shm-based nonblocking lock API Table of Contents
StatusThis library is still under early development and is production ready. Synopsis# nginx.conf
http {
# you do not need the following line if you are using the
# OpenResty bundle:
lua_package_path "/path/to/lua-resty-core/lib/?.lua;/path/to/lua-resty-lock/lib/?.lua;;";
lua_shared_dict my_locks 100k;
server {
...
location = /t {
content_by_lua '
local resty_lock = require "resty.lock"
for i = 1, 2 do
local lock, err = resty_lock:new("my_locks")
if not lock then
ngx.say("failed to create lock: ", err)
end
local elapsed, err = lock:lock("my_key")
ngx.say("lock: ", elapsed, ", ", err)
local ok, err = lock:unlock()
if not ok then
ngx.say("failed to unlock: ", err)
end
ngx.say("unlock: ", ok)
end
';
}
}
} DescriptionThis library implements a simple mutex lock in a similar way to ngx_proxy module's proxy_cache_lock directive. Under the hood, this library uses ngx_lua module's shared memory dictionaries. The lock waiting is nonblocking because we use stepwise ngx.sleep to poll the lock periodically. MethodsTo load this library,
local lock = require "resty.lock" new
Creates a new lock object instance by specifying the shared dictionary name (created by lua_shared_dict) and an optional options table In case of failure, returns The options table accepts the following options:
lock
Tries to lock a key across all the Nginx worker processes in the current Nginx server instance. Different keys are different locks. The length of the key string must not be larger than 65535 bytes. Returns the waiting time (in seconds) if the lock is successfully acquired. Otherwise returns The waiting time is not from the wallclock, but rather is from simply adding up all the waiting "steps". A nonzero When this method is waiting on fetching the lock, no operating system threads will be blocked and the current Lua "light thread" will be automatically yielded behind the scene. It is strongly recommended to always call the unlock() method to actively release the lock as soon as possible. If the unlock() method is never called after this method call, the lock will get released when
Common errors for this method call is
Other possible errors are from ngx_lua's shared dictionary API. It is required to create different unlock
Releases the lock held by the current Returns If you call expire
Sets the TTL of the lock held by the current Note that the Returns If you call For Multiple Lua Light ThreadsIt is always a bad idea to share a single For Cache LocksOne common use case for this library is avoid the so-called "dog-pile effect", that is, to limit concurrent backend queries for the same key when a cache miss happens. This usage is similar to the standard ngx_proxy module's proxy_cache_lock directive. The basic workflow for a cache lock is as follows:
Below is a kinda complete code example that demonstrates the idea. 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
-- FIXME: we should handle the backend miss more carefully
-- here, like inserting a stub value into the cache.
ngx.say("no value found")
return
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) Here we assume that we use the ngx_lua shared memory dictionary to cache the Redis query results and we have the following configurations in # you may want to change the dictionary size for your cases.
lua_shared_dict my_cache 10m;
lua_shared_dict my_locks 1m; The Several important things to note in the example above:
LimitationsSome of this library's API functions may yield. So do not call those functions in PrerequisitesInstallationIt is recommended to use the latest OpenResty bundle directly where this library
is bundled and enabled by default. At least OpenResty 1.4.2.9 is required. And you need to enable LuaJIT when building your OpenResty
bundle by passing the If you want to use this library with your own Nginx build (with ngx_lua), then you need to ensure you are using at least ngx_lua 0.8.10. Also, You need to configure the lua_package_path directive to add the path of your lua-resty-lock and lua-resty-core source directories to ngx_lua's Lua module search path, as in # nginx.conf
http {
lua_package_path "/path/to/lua-resty-lock/lib/?.lua;/path/to/lua-resty-core/lib/?.lua;;";
...
} and then load the library in Lua: local resty_lock = require "resty.lock" Note that this library depends on the lua-resty-core library which is also enabled by default in the OpenResty bundle. TODO
CommunityEnglish Mailing ListThe openresty-en mailing list is for English speakers. Chinese Mailing ListThe openresty mailing list is for Chinese speakers. Bugs and PatchesPlease report bugs or submit patches by
AuthorYichun "agentzh" Zhang (章亦春) [email protected], OpenResty Inc. Copyright and LicenseThis module is licensed under the BSD license. Copyright (C) 2013-2019, by Yichun "agentzh" Zhang, OpenResty Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. See Also
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论