{"id":13635940,"url":"https://github.com/openresty/lua-resty-lrucache","last_synced_at":"2025-04-19T04:31:45.153Z","repository":{"id":16542700,"uuid":"19296238","full_name":"openresty/lua-resty-lrucache","owner":"openresty","description":"Lua-land LRU Cache based on LuaJIT FFI","archived":false,"fork":false,"pushed_at":"2024-03-18T07:57:40.000Z","size":111,"stargazers_count":432,"open_issues_count":13,"forks_count":106,"subscribers_count":28,"default_branch":"master","last_synced_at":"2024-03-18T08:56:17.803Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Lua","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"socketio/socket.io-client-swift","license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/openresty.png","metadata":{"files":{"readme":"README.markdown","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-04-30T00:43:42.000Z","updated_at":"2024-06-18T22:52:04.758Z","dependencies_parsed_at":"2023-02-10T21:15:21.937Z","dependency_job_id":"6c296ed3-7676-44dc-a2e8-2ec7cdf0d7b7","html_url":"https://github.com/openresty/lua-resty-lrucache","commit_stats":{"total_commits":107,"total_committers":17,"mean_commits":6.294117647058823,"dds":0.3551401869158879,"last_synced_commit":"274244e0d7e94f7ad3407dbf358d9886a9d56b3b"},"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openresty%2Flua-resty-lrucache","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openresty%2Flua-resty-lrucache/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openresty%2Flua-resty-lrucache/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openresty%2Flua-resty-lrucache/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/openresty","download_url":"https://codeload.github.com/openresty/lua-resty-lrucache/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223790512,"owners_count":17203355,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-02T00:00:54.407Z","updated_at":"2024-11-09T05:31:08.245Z","avatar_url":"https://github.com/openresty.png","language":"Lua","funding_links":[],"categories":["Libraries","Third Modules","Rust Modules","Lua"],"sub_categories":["C Modules","Lua Modules"],"readme":"Name\n====\n\nlua-resty-lrucache - Lua-land LRU cache based on the LuaJIT FFI.\n\nTable of Contents\n=================\n\n* [Name](#name)\n* [Status](#status)\n* [Synopsis](#synopsis)\n* [Description](#description)\n* [Methods](#methods)\n    * [new](#new)\n    * [set](#set)\n    * [get](#get)\n    * [delete](#delete)\n    * [count](#count)\n    * [capacity](#capacity)\n    * [get_keys](#get_keys)\n    * [flush_all](#flush_all)\n* [Prerequisites](#prerequisites)\n* [Installation](#installation)\n* [Community](#community)\n    * [English Mailing List](#english-mailing-list)\n    * [Chinese Mailing List](#chinese-mailing-list)\n* [Bugs and Patches](#bugs-and-patches)\n* [Author](#author)\n* [Copyright and License](#copyright-and-license)\n* [See Also](#see-also)\n\nStatus\n======\n\nThis library is considered production ready.\n\nSynopsis\n========\n\n```lua\n-- file myapp.lua: example \"myapp\" module\n\nlocal _M = {}\n\n-- alternatively: local lrucache = require \"resty.lrucache.pureffi\"\nlocal lrucache = require \"resty.lrucache\"\n\n-- we need to initialize the cache on the lua module level so that\n-- it can be shared by all the requests served by each nginx worker process:\nlocal c, err = lrucache.new(200)  -- allow up to 200 items in the cache\nif not c then\n    error(\"failed to create the cache: \" .. (err or \"unknown\"))\nend\n\nfunction _M.go()\n    c:set(\"dog\", 32)\n    c:set(\"cat\", 56)\n    ngx.say(\"dog: \", c:get(\"dog\"))\n    ngx.say(\"cat: \", c:get(\"cat\"))\n\n    c:set(\"dog\", { age = 10 }, 0.1)  -- expire in 0.1 sec\n    c:delete(\"dog\")\n\n    c:flush_all()  -- flush all the cached data\nend\n\nreturn _M\n```\n\n```nginx\n# nginx.conf\n\nhttp {\n    # only if not using an official OpenResty release\n    lua_package_path \"/path/to/lua-resty-lrucache/lib/?.lua;;\";\n\n    server {\n        listen 8080;\n\n        location = /t {\n            content_by_lua_block {\n                require(\"myapp\").go()\n            }\n        }\n    }\n}\n```\n\nDescription\n===========\n\nThis library implements a simple LRU cache for\n[OpenResty](https://openresty.org) and the\n[ngx_lua](https://github.com/openresty/lua-nginx-module) module.\n\nThis cache also supports expiration time.\n\nThe LRU cache resides completely in the Lua VM and is subject to Lua GC. As\nsuch, do not expect it to get shared across the OS process boundary. The upside\nis that you can cache arbitrary complex Lua values (such as deep nested Lua\ntables) without the overhead of serialization (as with `ngx_lua`'s [shared\ndictionary\nAPI](https://github.com/openresty/lua-nginx-module#lua_shared_dict)).\nThe downside is that your cache is always limited to the current OS process\n(i.e. the current Nginx worker process). It does not really make much sense to\nuse this library in the context of\n[init_by_lua](https://github.com/openresty/lua-nginx-module#lua_shared_dict)\nbecause the cache will not get shared by any of the worker processes (unless\nyou just want to \"warm up\" the cache with predefined items which will get\ninherited by the workers via `fork()`).\n\nThis library offers two different implementations in the form of two classes:\n`resty.lrucache` and `resty.lrucache.pureffi`. Both implement the same API.\nThe only difference is that the latter is a pure FFI implementation that also\nimplements an FFI-based hash table for the cache lookup, while the former uses\nnative Lua tables.\n\nIf the cache hit rate is relatively high, you should use the `resty.lrucache`\nclass which is faster than `resty.lrucache.pureffi`.\n\nHowever, if the cache hit rate is relatively low and there can be a *lot* of\nvariations of keys inserted into and removed from the cache, then you should\nuse the `resty.lrucache.pureffi` instead, because Lua tables are not good at\nremoving keys frequently. You would likely see the `resizetab` function call in\nthe LuaJIT runtime being very hot in [on-CPU flame\ngraphs](https://github.com/openresty/stapxx#lj-lua-stacks) if you use the\n`resty.lrucache` class instead of `resty.lrucache.pureffi` in such a use case.\n\n[Back to TOC](#table-of-contents)\n\nMethods\n=======\n\nTo load this library,\n\n1. use an official [OpenResty release](https://openresty.org) or follow the\n   [Installation](#installation) instructions.\n2. use `require` to load the library into a local Lua variable:\n\n```lua\nlocal lrucache = require \"resty.lrucache\"\n```\n\nor\n\n```lua\nlocal lrucache = require \"resty.lrucache.pureffi\"\n```\n\n[Back to TOC](#table-of-contents)\n\nnew\n---\n`syntax: cache, err = lrucache.new(max_items [, load_factor])`\n\nCreates a new cache instance. Upon failure, returns `nil` and a string\ndescribing the error.\n\nThe `max_items` argument specifies the maximal number of items this cache can\nhold.\n\nThe `load-factor` argument designates the \"load factor\" of the FFI-based\nhash-table used internally by `resty.lrucache.pureffi`; the default value is\n0.5 (i.e. 50%); if the load factor is specified, it will be clamped to the\nrange of `[0.1, 1]` (i.e. if load factor is greater than 1, it will be\nsaturated to 1; likewise, if load-factor is smaller than `0.1`, it will be\nclamped to `0.1`). This argument is only meaningful for\n`resty.lrucache.pureffi`.\n\n[Back to TOC](#table-of-contents)\n\nset\n---\n`syntax: cache:set(key, value, ttl?, flags?)`\n\nSets a key with a value and an expiration time.\n\nWhen the cache is full, the cache will automatically evict the least recently\nused item.\n\nThe optional `ttl` argument specifies the expiration time. The time value is in\nseconds, but you can also specify the fraction number part (e.g. `0.25`). A nil\n`ttl` argument means the value would never expire (which is the default).\n\nThe optional `flags` argument specifies a user flags value associated with the\nitem to be stored. It can be retrieved later with the item. The user flags are\nstored as an unsigned 32-bit integer internally, and thus must be specified as\na Lua number. If not specified, flags will have a default value of `0`. This\nargument was added in the `v0.10` release.\n\n[Back to TOC](#table-of-contents)\n\nget\n---\n`syntax: data, stale_data, flags = cache:get(key)`\n\nFetches a value with the key. If the key does not exist in the cache or has\nalready expired, `nil` will be returned.\n\nStarting from `v0.03`, the stale data is also returned as the second return\nvalue if available.\n\nStarting from `v0.10`, the user flags value associated with the stored item is\nalso returned as the third return value. If no user flags were given to an\nitem, its default flags will be `0`.\n\n[Back to TOC](#table-of-contents)\n\ndelete\n------\n`syntax: cache:delete(key)`\n\nRemoves an item specified by the key from the cache.\n\n[Back to TOC](#table-of-contents)\n\ncount\n-----\n`syntax: count = cache:count()`\n\nReturns the number of items currently stored in the cache **including**\nexpired items if any.\n\nThe returned `count` value will always be greater or equal to 0 and smaller\nthan or equal to the `size` argument given to [`cache:new`](#new).\n\nThis method was added in the `v0.10` release.\n\n[Back to TOC](#table-of-contents)\n\ncapacity\n--------\n`syntax: size = cache:capacity()`\n\nReturns the maximum number of items the cache can hold. The return value is the\nsame as the `size` argument given to [`cache:new`](#new) when the cache was\ncreated.\n\nThis method was added in the `v0.10` release.\n\n[Back to TOC](#table-of-contents)\n\nget_keys\n--------\n`syntax: keys = cache:get_keys(max_count?, res?)`\n\nFetch the list of keys currently inside the cache up to `max_count`. The keys\nwill be ordered in MRU fashion (Most-Recently-Used keys first).\n\nThis function returns a Lua (array) table (with integer keys) containing the\nkeys.\n\nWhen `max_count` is `nil` or `0`, all keys (if any) will be returned.\n\nWhen provided with a `res` table argument, this function will not allocate a\ntable and will instead insert the keys in `res`, along with a trailing `nil`\nvalue.\n\nThis method was added in the `v0.10` release.\n\n[Back to TOC](#table-of-contents)\n\nflush_all\n---------\n`syntax: cache:flush_all()`\n\nFlushes all the existing data (if any) in the current cache instance. This is\nan `O(1)` operation and should be much faster than creating a brand new cache\ninstance.\n\nNote however that the `flush_all()` method of `resty.lrucache.pureffi` is an\n`O(n)` operation.\n\n[Back to TOC](#table-of-contents)\n\nPrerequisites\n=============\n\n* [LuaJIT](http://luajit.org) 2.0+\n* [ngx_lua](https://github.com/openresty/lua-nginx-module) 0.8.10+\n\n[Back to TOC](#table-of-contents)\n\nInstallation\n============\n\nIt is recommended to use the latest [OpenResty release](https://openresty.org).\nAt least OpenResty 1.4.2.9 is required. Recent versions of OpenResty only\nsupport LuaJIT, but if you are using an older version, make sure to enable\nLuaJIT when building OpenResty by passing the `--with-luajit` option to its\n`./configure` script. No extra Nginx configuration is required.\n\nIf you want to use this library with your own Nginx build (with ngx_lua), then\nyou need to ensure you are using ngx_lua 0.8.10 or greater.\n\nBy default, ngx_lua will search Lua files in /usr/local/share/lua/5.1/.\nBut `make install` will install this module to /usr/local/lib/lua.\nSo you may find the error like this:\n\n```text\nnginx: [alert] failed to load the 'resty.lrucache' module\n```\n\nYou can install this module with the following command to resolve the above problem.\n\n```bash\ncd lua-resty-lrucache\nsudo make install LUA_LIB_DIR=/usr/local/share/lua/5.1\n```\n\nYou can also change the installation directory to any other directory you like with the LUA_LIB_DIR argument.\n\n```bash\ncd lua-resty-lrucache\nsudo make install LUA_LIB_DIR=/opt/nginx/lualib\n```\n\nWhen not installed in /usr/local/share/lua/5.1, you also need to configure the\n[lua_package_path](https://github.com/openresty/lua-nginx-module#lua_package_path)\ndirective to add the path to your lua-resty-lrucache source tree to ngx_lua's\nLua module search path, as in:\n\n```nginx\n# nginx.conf\n\n    http {\n        lua_package_path \"/opt/nginx/lualib/?.lua;;\";\n        ...\n    }\n```\n\nand then load the library in Lua:\n\n```lua\nlocal lrucache = require \"resty.lrucache\"\n```\n\n[Back to TOC](#table-of-contents)\n\nCommunity\n=========\n\n[Back to TOC](#table-of-contents)\n\nEnglish Mailing List\n--------------------\n\nThe [openresty-en](https://groups.google.com/group/openresty-en) mailing list\nis for English speakers.\n\n[Back to TOC](#table-of-contents)\n\nChinese Mailing List\n--------------------\n\nThe [openresty](https://groups.google.com/group/openresty) mailing list is for\nChinese speakers.\n\n[Back to TOC](#table-of-contents)\n\nBugs and Patches\n================\n\nPlease report bugs or submit patches by\n\n1. creating a ticket on the [GitHub Issue\n   Tracker](https://github.com/openresty/lua-resty-lrucache/issues),\n1. or posting to the [OpenResty community](#community).\n\n[Back to TOC](#table-of-contents)\n\nAuthor\n======\n\nYichun \"agentzh\" Zhang (章亦春) \u003cagentzh@gmail.com\u003e, OpenResty Inc.\n\nShuxin Yang.\n\n[Back to TOC](#table-of-contents)\n\nCopyright and License\n=====================\n\nThis module is licensed under the BSD license.\n\nCopyright (C) 2014-2019, by Yichun \"agentzh\" Zhang, OpenResty Inc.\n\nCopyright (C) 2014-2017, by Shuxin Yang.\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\nTHIS 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.\n\n[Back to TOC](#table-of-contents)\n\nSee Also\n========\n\n* OpenResty: https://openresty.org\n* the ngx_http_lua module: https://github.com/openresty/lua-nginx-module\n* the ngx_stream_lua module: https://github.com/openresty/stream-lua-nginx-module\n* the lua-resty-core library: https://github.com/openresty/lua-resty-core\n\n[Back to TOC](#table-of-contents)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenresty%2Flua-resty-lrucache","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fopenresty%2Flua-resty-lrucache","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenresty%2Flua-resty-lrucache/lists"}