{"id":13635978,"url":"https://github.com/openresty/lua-resty-redis","last_synced_at":"2025-05-14T04:10:13.997Z","repository":{"id":41844682,"uuid":"3366743","full_name":"openresty/lua-resty-redis","owner":"openresty","description":"Lua redis client driver for the ngx_lua based on the cosocket API","archived":false,"fork":false,"pushed_at":"2025-03-07T11:18:09.000Z","size":238,"stargazers_count":1927,"open_issues_count":76,"forks_count":450,"subscribers_count":107,"default_branch":"master","last_synced_at":"2025-04-10T22:35:12.935Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Lua","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"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,"zenodo":null}},"created_at":"2012-02-06T12:24:25.000Z","updated_at":"2025-04-04T17:46:21.000Z","dependencies_parsed_at":"2024-04-26T01:37:07.972Z","dependency_job_id":"e241b769-24e8-4d7a-a478-4f054cd25e58","html_url":"https://github.com/openresty/lua-resty-redis","commit_stats":{"total_commits":201,"total_committers":26,"mean_commits":7.730769230769231,"dds":"0.22885572139303478","last_synced_commit":"6d1d36c700b99b3f93f2fec9a677ae0aeb700286"},"previous_names":[],"tags_count":35,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openresty%2Flua-resty-redis","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openresty%2Flua-resty-redis/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openresty%2Flua-resty-redis/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openresty%2Flua-resty-redis/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/openresty","download_url":"https://codeload.github.com/openresty/lua-resty-redis/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254070111,"owners_count":22009559,"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.850Z","updated_at":"2025-05-14T04:10:08.973Z","avatar_url":"https://github.com/openresty.png","language":"Lua","funding_links":[],"categories":["Libraries","Third Modules","Lua","Rust Modules","资源","Resources"],"sub_categories":["C Modules","Lua Modules","Data Stores"],"readme":"Name\n====\n\nlua-resty-redis - Lua redis client driver for the ngx_lua based on the cosocket API\n\nTable of Contents\n=================\n\n* [Name](#name)\n* [Status](#status)\n* [Description](#description)\n* [Synopsis](#synopsis)\n* [Methods](#methods)\n    * [new](#new)\n    * [connect](#connect)\n    * [set_timeout](#set_timeout)\n    * [set_timeouts](#set_timeouts)\n    * [set_keepalive](#set_keepalive)\n    * [get_reused_times](#get_reused_times)\n    * [close](#close)\n    * [init_pipeline](#init_pipeline)\n    * [commit_pipeline](#commit_pipeline)\n    * [cancel_pipeline](#cancel_pipeline)\n    * [hmset](#hmset)\n    * [array_to_hash](#array_to_hash)\n    * [read_reply](#read_reply)\n    * [add_commands](#add_commands)\n* [Redis Authentication](#redis-authentication)\n* [Redis Transactions](#redis-transactions)\n* [Load Balancing and Failover](#load-balancing-and-failover)\n* [Debugging](#debugging)\n* [Automatic Error Logging](#automatic-error-logging)\n* [Check List for Issues](#check-list-for-issues)\n* [Limitations](#limitations)\n* [Installation](#installation)\n* [TODO](#todo)\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\nDescription\n===========\n\nThis Lua library is a Redis client driver for the ngx_lua nginx module:\n\nhttps://github.com/openresty/lua-nginx-module/#readme\n\nThis Lua library takes advantage of ngx_lua's cosocket API, which ensures\n100% nonblocking behavior.\n\nNote that at least [ngx_lua 0.5.14](https://github.com/chaoslawful/lua-nginx-module/tags) or [OpenResty 1.2.1.14](http://openresty.org/#Download) is required.\n\nSynopsis\n========\n\n```lua\n    # you do not need the following line if you are using\n    # the OpenResty bundle:\n    lua_package_path \"/path/to/lua-resty-redis/lib/?.lua;;\";\n\n    server {\n        location /test {\n            # need to specify the resolver to resolve the hostname\n            resolver 8.8.8.8;\n\n            content_by_lua_block {\n                local redis = require \"resty.redis\"\n                local red = redis:new()\n\n                red:set_timeouts(1000, 1000, 1000) -- 1 sec\n\n                -- or connect to a unix domain socket file listened\n                -- by a redis server:\n                --     local ok, err = red:connect(\"unix:/path/to/redis.sock\")\n\n                -- connect via ip address directly\n                local ok, err = red:connect(\"127.0.0.1\", 6379)\n\n                -- or connect via hostname, need to specify resolver just like above\n                local ok, err = red:connect(\"redis.openresty.com\", 6379)\n\n                if not ok then\n                    ngx.say(\"failed to connect: \", err)\n                    return\n                end\n\n                ok, err = red:set(\"dog\", \"an animal\")\n                if not ok then\n                    ngx.say(\"failed to set dog: \", err)\n                    return\n                end\n\n                ngx.say(\"set result: \", ok)\n\n                local res, err = red:get(\"dog\")\n                if not res then\n                    ngx.say(\"failed to get dog: \", err)\n                    return\n                end\n\n                if res == ngx.null then\n                    ngx.say(\"dog not found.\")\n                    return\n                end\n\n                ngx.say(\"dog: \", res)\n\n                red:init_pipeline()\n                red:set(\"cat\", \"Marry\")\n                red:set(\"horse\", \"Bob\")\n                red:get(\"cat\")\n                red:get(\"horse\")\n                local results, err = red:commit_pipeline()\n                if not results then\n                    ngx.say(\"failed to commit the pipelined requests: \", err)\n                    return\n                end\n\n                for i, res in ipairs(results) do\n                    if type(res) == \"table\" then\n                        if res[1] == false then\n                            ngx.say(\"failed to run command \", i, \": \", res[2])\n                        else\n                            -- process the table value\n                        end\n                    else\n                        -- process the scalar value\n                    end\n                end\n\n                -- put it into the connection pool of size 100,\n                -- with 10 seconds max idle time\n                local ok, err = red:set_keepalive(10000, 100)\n                if not ok then\n                    ngx.say(\"failed to set keepalive: \", err)\n                    return\n                end\n\n                -- or just close the connection right away:\n                -- local ok, err = red:close()\n                -- if not ok then\n                --     ngx.say(\"failed to close: \", err)\n                --     return\n                -- end\n            }\n        }\n    }\n```\n\n[Back to TOC](#table-of-contents)\n\nMethods\n=======\n\nAll of the Redis commands have their own methods with the same name except all in lower case.\n\nYou can find the complete list of Redis commands here:\n\nhttp://redis.io/commands\n\nYou need to check out this Redis command reference to see what Redis command accepts what arguments.\n\nThe Redis command arguments can be directly fed into the corresponding method call. For example, the \"GET\" redis command accepts a single key argument, then you can just call the \"get\" method like this:\n\n```lua\n    local res, err = red:get(\"key\")\n```\n\nSimilarly, the \"LRANGE\" redis command accepts three arguments, then you should call the \"lrange\" method like this:\n\n```lua\n    local res, err = red:lrange(\"nokey\", 0, 1)\n```\n\nFor example, \"SET\", \"GET\", \"LRANGE\", and \"BLPOP\" commands correspond to the methods \"set\", \"get\", \"lrange\", and \"blpop\".\n\nHere are some more examples:\n\n```lua\n    -- HMGET myhash field1 field2 nofield\n    local res, err = red:hmget(\"myhash\", \"field1\", \"field2\", \"nofield\")\n```\n\n```lua\n    -- HMSET myhash field1 \"Hello\" field2 \"World\"\n    local res, err = red:hmset(\"myhash\", \"field1\", \"Hello\", \"field2\", \"World\")\n```\n\nAll these command methods returns a single result in success and `nil` otherwise. In case of errors or failures, it will also return a second value which is a string describing the error.\n\nA Redis \"status reply\" results in a string typed return value with the \"+\" prefix stripped.\n\nA Redis \"integer reply\" results in a Lua number typed return value.\n\nA Redis \"error reply\" results in a `false` value *and* a string describing the error.\n\nA non-nil Redis \"bulk reply\" results in a Lua string as the return value. A nil bulk reply results in a `ngx.null` return value.\n\nA non-nil Redis \"multi-bulk reply\" results in a Lua table holding all the composing values (if any). If any of the composing value is a valid redis error value, then it will be a two element table `{false, err}`.\n\nA nil multi-bulk reply returns in a `ngx.null` value.\n\nSee http://redis.io/topics/protocol for details regarding various Redis reply types.\n\nIn addition to all those redis command methods, the following methods are also provided:\n\n[Back to TOC](#table-of-contents)\n\nnew\n---\n`syntax: red, err = redis:new()`\n\nCreates a redis object. In case of failures, returns `nil` and a string describing the error.\n\n[Back to TOC](#table-of-contents)\n\nconnect\n-------\n`syntax: ok, err = red:connect(host, port, options_table?)`\n\n`syntax: ok, err = red:connect(\"unix:/path/to/unix.sock\", options_table?)`\n\nAttempts to connect to the remote host and port that the redis server is listening to or a local unix domain socket file listened by the redis server.\n\nBefore actually resolving the host name and connecting to the remote backend, this method will always look up the connection pool for matched idle connections created by previous calls of this method.\n\nThe optional `options_table` argument is a Lua table holding the following keys:\n\n* `ssl`\n\n    If set to true, then uses SSL to connect to redis (defaults to false).\n\n* `ssl_verify`\n\n    If set to true, then verifies the validity of the server SSL certificate (defaults to false). Note that you need to configure the lua_ssl_trusted_certificate to specify the CA (or server) certificate used by your redis server. You may also need to configure lua_ssl_verify_depth accordingly.\n\n* `server_name`\n\n    Specifies the server name for the new TLS extension Server Name Indication (SNI) when connecting over SSL.\n\n* `pool`\n\n    Specifies a custom name for the connection pool being used. If omitted, then the connection pool name will be generated from the string template `\u003chost\u003e:\u003cport\u003e` or `\u003cunix-socket-path\u003e`.\n\n* `pool_size`\n\n    Specifies the size of the connection pool. If omitted and no `backlog` option was provided, no pool will be created. If omitted but `backlog` was provided, the pool will be created with a default size equal to the value of the [lua_socket_pool_size](https://github.com/openresty/lua-nginx-module#lua_socket_pool_size) directive. The connection pool holds up to `pool_size` alive connections ready to be reused by subsequent calls to [connect](#connect), but note that there is no upper limit to the total number of opened connections outside of the pool. If you need to restrict the total number of opened connections, specify the `backlog` option. When the connection pool would exceed its size limit, the least recently used (kept-alive) connection already in the pool will be closed to make room for the current connection. Note that the cosocket connection pool is per Nginx worker process rather than per Nginx server instance, so the size limit specified here also applies to every single Nginx worker process. Also note that the size of the connection pool cannot be changed once it has been created. Note that at least [ngx_lua 0.10.14](https://github.com/openresty/lua-nginx-module/tags) is required to use this options.\n\n* `backlog`\n\n    If specified, this module will limit the total number of opened connections for this pool. No more connections than `pool_size` can be opened for this pool at any time. If the connection pool is full, subsequent connect operations will be queued into a queue equal to this option's value (the \"backlog\" queue). If the number of queued connect operations is equal to `backlog`, subsequent connect operations will fail and return nil plus the error string `\"too many waiting connect operations\"`. The queued connect operations will be resumed once the number of connections in the pool is less than `pool_size`. The queued connect operation will abort once they have been queued for more than `connect_timeout`, controlled by [set_timeout](#set_timeout), and will return nil plus the error string \"timeout\". Note that at least [ngx_lua 0.10.14](https://github.com/openresty/lua-nginx-module/tags) is required to use this options.\n\n[Back to TOC](#table-of-contents)\n\nset_timeout\n-----------\n`syntax: red:set_timeout(time)`\n\nSets the timeout (in ms) protection for subsequent operations, including the `connect` method.\n\nSince version `v0.28` of this module, it is advised that\n[set_timeouts](#set_timeouts) be used in favor of this method.\n\n[Back to TOC](#table-of-contents)\n\nset_timeouts\n------------\n`syntax: red:set_timeouts(connect_timeout, send_timeout, read_timeout)`\n\nRespectively sets the connect, send, and read timeout thresholds (in ms), for\nsubsequent socket operations. Setting timeout thresholds with this method\noffers more granularity than [set_timeout](#set_timeout). As such, it is\npreferred to use [set_timeouts](#set_timeouts) over\n[set_timeout](#set_timeout).\n\nThis method was added in the `v0.28` release.\n\n[Back to TOC](#table-of-contents)\n\nset_keepalive\n-------------\n`syntax: ok, err = red:set_keepalive(max_idle_timeout, pool_size)`\n\nPuts the current Redis connection immediately into the ngx_lua cosocket connection pool.\n\nYou can specify the max idle timeout (in ms) when the connection is in the pool and the maximal size of the pool every nginx worker process.\n\nIn case of success, returns `1`. In case of errors, returns `nil` with a string describing the error.\n\nOnly call this method in the place you would have called the `close` method instead. Calling this method will immediately turn the current redis object into the `closed` state. Any subsequent operations other than `connect()` on the current object will return the `closed` error.\n\n[Back to TOC](#table-of-contents)\n\nget_reused_times\n----------------\n`syntax: times, err = red:get_reused_times()`\n\nThis method returns the (successfully) reused times for the current connection. In case of error, it returns `nil` and a string describing the error.\n\nIf the current connection does not come from the built-in connection pool, then this method always returns `0`, that is, the connection has never been reused (yet). If the connection comes from the connection pool, then the return value is always non-zero. So this method can also be used to determine if the current connection comes from the pool.\n\n[Back to TOC](#table-of-contents)\n\nclose\n-----\n`syntax: ok, err = red:close()`\n\nCloses the current redis connection and returns the status.\n\nIn case of success, returns `1`. In case of errors, returns `nil` with a string describing the error.\n\n[Back to TOC](#table-of-contents)\n\ninit_pipeline\n-------------\n`syntax: red:init_pipeline()`\n\n`syntax: red:init_pipeline(n)`\n\nEnable the redis pipelining mode. All subsequent calls to Redis command methods will automatically get cached and will send to the server in one run when the `commit_pipeline` method is called or get cancelled by calling the `cancel_pipeline` method.\n\nThis method always succeeds.\n\nIf the redis object is already in the Redis pipelining mode, then calling this method will discard existing cached Redis queries.\n\nThe optional `n` argument specifies the (approximate) number of commands that are going to add to this pipeline, which can make things a little faster.\n\n[Back to TOC](#table-of-contents)\n\ncommit_pipeline\n---------------\n`syntax: results, err = red:commit_pipeline()`\n\nQuits the pipelining mode by committing all the cached Redis queries to the remote server in a single run. All the replies for these queries will be collected automatically and are returned as if a big multi-bulk reply at the highest level.\n\nThis method returns `nil` and a Lua string describing the error upon failures.\n\n[Back to TOC](#table-of-contents)\n\ncancel_pipeline\n---------------\n`syntax: red:cancel_pipeline()`\n\nQuits the pipelining mode by discarding all existing cached Redis commands since the last call to the `init_pipeline` method.\n\nThis method always succeeds.\n\nIf the redis object is not in the Redis pipelining mode, then this method is a no-op.\n\n[Back to TOC](#table-of-contents)\n\nhmset\n-----\n`syntax: res, err = red:hmset(myhash, field1, value1, field2, value2, ...)`\n\n`syntax: res, err = red:hmset(myhash, { field1 = value1, field2 = value2, ... })`\n\nSpecial wrapper for the Redis \"hmset\" command.\n\nWhen there are only three arguments (including the \"red\" object\nitself), then the last argument must be a Lua table holding all the field/value pairs.\n\n[Back to TOC](#table-of-contents)\n\narray_to_hash\n-------------\n`syntax: hash = red:array_to_hash(array)`\n\nAuxiliary function that converts an array-like Lua table into a hash-like table.\n\nThis method was first introduced in the `v0.11` release.\n\n[Back to TOC](#table-of-contents)\n\nread_reply\n----------\n`syntax: res, err = red:read_reply()`\n\nReading a reply from the redis server. This method is mostly useful for the [Redis Pub/Sub API](http://redis.io/topics/pubsub/), for example,\n\n```lua\n    local cjson = require \"cjson\"\n    local redis = require \"resty.redis\"\n\n    local red = redis:new()\n    local red2 = redis:new()\n\n    red:set_timeouts(1000, 1000, 1000) -- 1 sec\n    red2:set_timeouts(1000, 1000, 1000) -- 1 sec\n\n    local ok, err = red:connect(\"127.0.0.1\", 6379)\n    if not ok then\n        ngx.say(\"1: failed to connect: \", err)\n        return\n    end\n\n    ok, err = red2:connect(\"127.0.0.1\", 6379)\n    if not ok then\n        ngx.say(\"2: failed to connect: \", err)\n        return\n    end\n\n    local res, err = red:subscribe(\"dog\")\n    if not res then\n        ngx.say(\"1: failed to subscribe: \", err)\n        return\n    end\n\n    ngx.say(\"1: subscribe: \", cjson.encode(res))\n\n    res, err = red2:publish(\"dog\", \"Hello\")\n    if not res then\n        ngx.say(\"2: failed to publish: \", err)\n        return\n    end\n\n    ngx.say(\"2: publish: \", cjson.encode(res))\n\n    res, err = red:read_reply()\n    if not res then\n        ngx.say(\"1: failed to read reply: \", err)\n        return\n    end\n\n    ngx.say(\"1: receive: \", cjson.encode(res))\n\n    red:close()\n    red2:close()\n```\n\nRunning this example gives the output like this:\n\n    1: subscribe: [\"subscribe\",\"dog\",1]\n    2: publish: 1\n    1: receive: [\"message\",\"dog\",\"Hello\"]\n\nThe following class methods are provieded:\n\n[Back to TOC](#table-of-contents)\n\nadd_commands\n------------\n`syntax: hash = redis.add_commands(cmd_name1, cmd_name2, ...)`\n\n*WARNING* this method is now deprecated since we already do automatic Lua method generation\nfor any redis commands the user attempts to use and thus we no longer need this.\n\nAdds new redis commands to the `resty.redis` class. Here is an example:\n\n```lua\n    local redis = require \"resty.redis\"\n\n    redis.add_commands(\"foo\", \"bar\")\n\n    local red = redis:new()\n\n    red:set_timeouts(1000, 1000, 1000) -- 1 sec\n\n    local ok, err = red:connect(\"127.0.0.1\", 6379)\n    if not ok then\n        ngx.say(\"failed to connect: \", err)\n        return\n    end\n\n    local res, err = red:foo(\"a\")\n    if not res then\n        ngx.say(\"failed to foo: \", err)\n    end\n\n    res, err = red:bar()\n    if not res then\n        ngx.say(\"failed to bar: \", err)\n    end\n```\n\n[Back to TOC](#table-of-contents)\n\nRedis Authentication\n====================\n\nRedis uses the `AUTH` command to do authentication: http://redis.io/commands/auth\n\nThere is nothing special for this command as compared to other Redis\ncommands like `GET` and `SET`. So one can just invoke the `auth` method on your `resty.redis` instance. Here is an example:\n\n```lua\n    local redis = require \"resty.redis\"\n    local red = redis:new()\n\n    red:set_timeouts(1000, 1000, 1000) -- 1 sec\n\n    local ok, err = red:connect(\"127.0.0.1\", 6379)\n    if not ok then\n        ngx.say(\"failed to connect: \", err)\n        return\n    end\n\n    local res, err = red:auth(\"foobared\")\n    if not res then\n        ngx.say(\"failed to authenticate: \", err)\n        return\n    end\n```\n\nwhere we assume that the Redis server is configured with the\npassword `foobared` in the `redis.conf` file:\n\n    requirepass foobared\n\nIf the password specified is wrong, then the sample above will output the\nfollowing to the HTTP client:\n\n    failed to authenticate: ERR invalid password\n\n[Back to TOC](#table-of-contents)\n\nRedis Transactions\n==================\n\nThis library supports the [Redis transactions](http://redis.io/topics/transactions/). Here is an example:\n\n```lua\n    local cjson = require \"cjson\"\n    local redis = require \"resty.redis\"\n    local red = redis:new()\n\n    red:set_timeouts(1000, 1000, 1000) -- 1 sec\n\n    local ok, err = red:connect(\"127.0.0.1\", 6379)\n    if not ok then\n        ngx.say(\"failed to connect: \", err)\n        return\n    end\n\n    local ok, err = red:multi()\n    if not ok then\n        ngx.say(\"failed to run multi: \", err)\n        return\n    end\n    ngx.say(\"multi ans: \", cjson.encode(ok))\n\n    local ans, err = red:set(\"a\", \"abc\")\n    if not ans then\n        ngx.say(\"failed to run sort: \", err)\n        return\n    end\n    ngx.say(\"set ans: \", cjson.encode(ans))\n\n    local ans, err = red:lpop(\"a\")\n    if not ans then\n        ngx.say(\"failed to run sort: \", err)\n        return\n    end\n    ngx.say(\"set ans: \", cjson.encode(ans))\n\n    ans, err = red:exec()\n    ngx.say(\"exec ans: \", cjson.encode(ans))\n\n    red:close()\n```\n\nThen the output will be\n\n    multi ans: \"OK\"\n    set ans: \"QUEUED\"\n    set ans: \"QUEUED\"\n    exec ans: [\"OK\",[false,\"ERR Operation against a key holding the wrong kind of value\"]]\n\n[Back to TOC](#table-of-contents)\n\nRedis Module\n==================\n\nThis library supports the Redis module. Here is an example with RedisBloom module:\n\n```lua\n    local cjson = require \"cjson\"\n    local redis = require \"resty.redis\"\n    -- register the module prefix \"bf\" for RedisBloom\n    redis.register_module_prefix(\"bf\")\n\n    local red = redis:new()\n\n    local ok, err = red:connect(\"127.0.0.1\", 6379)\n    if not ok then\n        ngx.say(\"failed to connect: \", err)\n        return\n    end\n\n    -- call BF.ADD command with the prefix 'bf'\n    res, err = red:bf():add(\"dog\", 1)\n    if not res then\n        ngx.say(err)\n        return\n    end\n    ngx.say(\"receive: \", cjson.encode(res))\n\n    -- call BF.EXISTS command\n    res, err = red:bf():exists(\"dog\")\n    if not res then\n        ngx.say(err)\n        return\n    end\n    ngx.say(\"receive: \", cjson.encode(res))\n```\n\nLoad Balancing and Failover\n===========================\n\nYou can trivially implement your own Redis load balancing logic yourself in Lua. Just keep a Lua table of all available Redis backend information (like host name and port numbers) and pick one server according to some rule (like round-robin or key-based hashing) from the Lua table at every request. You can keep track of the current rule state in your own Lua module's data, see https://github.com/openresty/lua-nginx-module/#data-sharing-within-an-nginx-worker\n\nSimilarly, you can implement automatic failover logic in Lua at great flexibility.\n\n[Back to TOC](#table-of-contents)\n\nDebugging\n=========\n\nIt is usually convenient to use the [lua-cjson](http://www.kyne.com.au/~mark/software/lua-cjson.php) library to encode the return values of the redis command methods to JSON. For example,\n\n```lua\n    local cjson = require \"cjson\"\n    ...\n    local res, err = red:mget(\"h1234\", \"h5678\")\n    if res then\n        print(\"res: \", cjson.encode(res))\n    end\n```\n\n[Back to TOC](#table-of-contents)\n\nAutomatic Error Logging\n=======================\n\nBy default the underlying [ngx_lua](https://github.com/openresty/lua-nginx-module/#readme) module\ndoes error logging when socket errors happen. If you are already doing proper error\nhandling in your own Lua code, then you are recommended to disable this automatic error logging by turning off [ngx_lua](https://github.com/openresty/lua-nginx-module/#readme)'s [lua_socket_log_errors](https://github.com/openresty/lua-nginx-module/#lua_socket_log_errors) directive, that is,\n\n```nginx\n    lua_socket_log_errors off;\n```\n\n[Back to TOC](#table-of-contents)\n\nCheck List for Issues\n=====================\n\n1. Ensure you configure the connection pool size properly in the [set_keepalive](#set_keepalive). Basically if your Redis can handle `n` concurrent connections and your NGINX has `m` workers, then the connection pool size should be configured as `n/m`. For example, if your Redis usually handles 1000 concurrent requests and you have 10 NGINX workers, then the connection pool size should be 100. Similarly if you have `p` different NGINX instances, then connection pool size should be `n/m/p`.\n2. Ensure the backlog setting on the Redis side is large enough. For Redis 2.8+, you can directly tune the `tcp-backlog` parameter in the `redis.conf` file (and also tune the kernel parameter `SOMAXCONN` accordingly at least on Linux). You may also want to tune the `maxclients` parameter in `redis.conf`.\n3. Ensure you are not using too short timeout setting in the [set_timeout](#set_timeout) or [set_timeouts](#set_timeouts) methods. If you have to, try redoing the operation upon timeout and turning off [automatic error logging](#automatic-error-logging) (because you are already doing proper error handling in your own Lua code).\n4. If your NGINX worker processes' CPU usage is very high under load, then the NGINX event loop might be blocked by the CPU computation too much. Try sampling a [C-land on-CPU Flame Graph](https://github.com/agentzh/nginx-systemtap-toolkit#sample-bt) and [Lua-land on-CPU Flame Graph](https://github.com/agentzh/stapxx#ngx-lj-lua-stacks) for a typical NGINX worker process. You can optimize the CPU-bound things according to these Flame Graphs.\n5. If your NGINX worker processes' CPU usage is very low under load, then the NGINX event loop might be blocked by some blocking system calls (like file IO system calls). You can confirm the issue by running the [epoll-loop-blocking-distr](https://github.com/agentzh/stapxx#epoll-loop-blocking-distr) tool against a typical NGINX worker process. If it is indeed the case, then you can further sample a [C-land off-CPU Flame Graph](https://github.com/agentzh/nginx-systemtap-toolkit#sample-bt-off-cpu) for a NGINX worker process to analyze the actual blockers.\n6. If your `redis-server` process is running near 100% CPU usage, then you should consider scale your Redis backend by multiple nodes or use the [C-land on-CPU Flame Graph tool](https://github.com/agentzh/nginx-systemtap-toolkit#sample-bt) to analyze the internal bottlenecks within the Redis server process.\n\n[Back to TOC](#table-of-contents)\n\nLimitations\n===========\n\n* This library cannot be used in code contexts like init_by_lua*, set_by_lua*, log_by_lua*, and\nheader_filter_by_lua* where the ngx_lua cosocket API is not available.\n* The `resty.redis` object instance cannot be stored in a Lua variable at the Lua module level,\nbecause it will then be shared by all the concurrent requests handled by the same nginx\n worker process (see\nhttps://github.com/openresty/lua-nginx-module/#data-sharing-within-an-nginx-worker ) and\nresult in bad race conditions when concurrent requests are trying to use the same `resty.redis` instance\n(you would see the \"bad request\" or \"socket busy\" error to be returned from the method calls).\nYou should always initiate `resty.redis` objects in function local\nvariables or in the `ngx.ctx` table. These places all have their own data copies for\neach request.\n\n[Back to TOC](#table-of-contents)\n\nInstallation - Build from source\n============\n\n```sh\n# Clone latest release , assuming v0.29\nwget https://github.com/openresty/lua-resty-redis/archive/refs/tags/v0.29.tar.gz\n\n# Extract\ntar -xvzf v0.29.tar.gz\n\n# go into directory\ncd lua-resty-redis-0.29\n\nexport LUA_LIB_DIR=/usr/local/openresty/site/lualib\n\n# Compile and Install\nmake install\n\n# Now compiled path will be outputted\n# /usr/local/lib/lua/resty = lua_package_path in nginx conf\n```\n\nInstallation Notes\n============\n\nIf you are using the OpenResty bundle (http://openresty.org ), then\nyou do not need to do anything because it already includes and enables\nlua-resty-redis by default. And you can just use it in your Lua code,\nas in\n\n```lua\n    local redis = require \"resty.redis\"\n    ...\n```\n\nIf you are using your own nginx + ngx_lua build, then you need to configure\nthe lua_package_path directive to add the path of your lua-resty-redis source\ntree to ngx_lua's LUA_PATH search path, as in\n\n```nginx\n    # nginx.conf\n    http {\n        lua_package_path \"/path/to/lua-resty-redis/lib/?.lua;;\";\n        ...\n    }\n```\n\nEnsure that the system account running your Nginx ''worker'' proceses have\nenough permission to read the `.lua` file.\n\n[Back to TOC](#table-of-contents)\n\nTODO\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 is 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 Chinese 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 Tracker](http://github.com/agentzh/lua-resty-redis/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\n[Back to TOC](#table-of-contents)\n\nCopyright and License\n=====================\n\nThis module is licensed under the BSD license.\n\nCopyright (C) 2012-2017, by Yichun Zhang (agentzh) \u003cagentzh@gmail.com\u003e, OpenResty Inc.\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* the ngx_lua module: https://github.com/openresty/lua-nginx-module/#readme\n* the redis wired protocol specification: http://redis.io/topics/protocol\n* the [lua-resty-memcached](https://github.com/agentzh/lua-resty-memcached) library\n* the [lua-resty-mysql](https://github.com/agentzh/lua-resty-mysql) library\n\n[Back to TOC](#table-of-contents)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenresty%2Flua-resty-redis","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fopenresty%2Flua-resty-redis","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenresty%2Flua-resty-redis/lists"}