pax_global_header00006660000000000000000000000064134302150110014500gustar00rootroot0000000000000052 comment=f3ecba8012b42d4817da44341a7c43961ad57690 lua-resty-redis-0.27/000077500000000000000000000000001343021501100144615ustar00rootroot00000000000000lua-resty-redis-0.27/.gitattributes000066400000000000000000000000331343021501100173500ustar00rootroot00000000000000*.t linguist-language=Text lua-resty-redis-0.27/.gitignore000066400000000000000000000000601343021501100164450ustar00rootroot00000000000000*.swp *.swo *~ go t/servroot/ reindex *.t_ tags lua-resty-redis-0.27/.travis.yml000066400000000000000000000047631343021501100166040ustar00rootroot00000000000000sudo: required dist: trusty os: linux language: c compiler: - gcc - clang services: - redis-server cache: directories: - download-cache env: global: - JOBS=3 - NGX_BUILD_JOBS=$JOBS - LUAJIT_PREFIX=/opt/luajit21 - LUAJIT_LIB=$LUAJIT_PREFIX/lib - LUAJIT_INC=$LUAJIT_PREFIX/include/luajit-2.1 - LUA_INCLUDE_DIR=$LUAJIT_INC - OPENSSL_PREFIX=/opt/ssl - OPENSSL_LIB=$OPENSSL_PREFIX/lib - OPENSSL_INC=$OPENSSL_PREFIX/include - OPENSSL_VER=1.0.2h - LD_LIBRARY_PATH=$LUAJIT_LIB:$LD_LIBRARY_PATH - TEST_NGINX_SLEEP=0.006 matrix: - NGINX_VERSION=1.9.15 # - NGINX_VERSION=1.10.0 install: - if [ ! -d download-cache ]; then mkdir download-cache; fi - if [ ! -f download-cache/openssl-$OPENSSL_VER.tar.gz ]; then wget -O download-cache/openssl-$OPENSSL_VER.tar.gz https://www.openssl.org/source/openssl-$OPENSSL_VER.tar.gz; fi - sudo apt-get install -qq -y cpanminus axel - sudo cpanm --notest Test::Nginx > build.log 2>&1 || (cat build.log && exit 1) - git clone https://github.com/openresty/openresty.git ../openresty - git clone https://github.com/openresty/nginx-devel-utils.git - git clone https://github.com/openresty/lua-cjson.git - git clone https://github.com/openresty/lua-nginx-module.git ../lua-nginx-module - git clone https://github.com/openresty/echo-nginx-module.git ../echo-nginx-module - git clone https://github.com/openresty/no-pool-nginx.git ../no-pool-nginx - git clone -b v2.1-agentzh https://github.com/openresty/luajit2.git script: - cd luajit2/ - make -j$JOBS CCDEBUG=-g Q= PREFIX=$LUAJIT_PREFIX CC=$CC XCFLAGS='-DLUA_USE_APICHECK -DLUA_USE_ASSERT' > build.log 2>&1 || (cat build.log && exit 1) - sudo make install PREFIX=$LUAJIT_PREFIX > build.log 2>&1 || (cat build.log && exit 1) - cd ../lua-cjson && make && sudo PATH=$PATH make install && cd .. - tar zxf download-cache/openssl-$OPENSSL_VER.tar.gz - cd openssl-$OPENSSL_VER/ - ./config shared --prefix=$OPENSSL_PREFIX -DPURIFY > build.log 2>&1 || (cat build.log && exit 1) - make -j$JOBS > build.log 2>&1 || (cat build.log && exit 1) - sudo make PATH=$PATH install_sw > build.log 2>&1 || (cat build.log && exit 1) - cd .. - export PATH=$PWD/work/nginx/sbin:$PWD/nginx-devel-utils:$PATH - export NGX_BUILD_CC=$CC - ngx-build $NGINX_VERSION --with-ipv6 --with-http_realip_module --with-http_ssl_module --add-module=../echo-nginx-module --add-module=../lua-nginx-module --with-debug - nginx -V - ldd `which nginx`|grep -E 'luajit|ssl|pcre' - prove -r t lua-resty-redis-0.27/Makefile000066400000000000000000000006471343021501100161300ustar00rootroot00000000000000OPENRESTY_PREFIX=/usr/local/openresty-debug PREFIX ?= /usr/local LUA_INCLUDE_DIR ?= $(PREFIX)/include LUA_LIB_DIR ?= $(PREFIX)/lib/lua/$(LUA_VERSION) INSTALL ?= install .PHONY: all test install all: ; install: all $(INSTALL) -d $(DESTDIR)$(LUA_LIB_DIR)/resty $(INSTALL) lib/resty/*.lua $(DESTDIR)$(LUA_LIB_DIR)/resty test: all PATH=$(OPENRESTY_PREFIX)/nginx/sbin:$$PATH prove -I../test-nginx/lib -r t lua-resty-redis-0.27/README.markdown000066400000000000000000000603461343021501100171730ustar00rootroot00000000000000Name ==== lua-resty-redis - Lua redis client driver for the ngx_lua based on the cosocket API Table of Contents ================= * [Name](#name) * [Status](#status) * [Description](#description) * [Synopsis](#synopsis) * [Methods](#methods) * [new](#new) * [connect](#connect) * [set_timeout](#set_timeout) * [set_keepalive](#set_keepalive) * [get_reused_times](#get_reused_times) * [close](#close) * [init_pipeline](#init_pipeline) * [commit_pipeline](#commit_pipeline) * [cancel_pipeline](#cancel_pipeline) * [hmset](#hmset) * [array_to_hash](#array_to_hash) * [read_reply](#read_reply) * [add_commands](#add_commands) * [Redis Authentication](#redis-authentication) * [Redis Transactions](#redis-transactions) * [Load Balancing and Failover](#load-balancing-and-failover) * [Debugging](#debugging) * [Automatic Error Logging](#automatic-error-logging) * [Check List for Issues](#check-list-for-issues) * [Limitations](#limitations) * [Installation](#installation) * [TODO](#todo) * [Community](#community) * [English Mailing List](#english-mailing-list) * [Chinese Mailing List](#chinese-mailing-list) * [Bugs and Patches](#bugs-and-patches) * [Author](#author) * [Copyright and License](#copyright-and-license) * [See Also](#see-also) Status ====== This library is considered production ready. Description =========== This Lua library is a Redis client driver for the ngx_lua nginx module: https://github.com/openresty/lua-nginx-module/#readme This Lua library takes advantage of ngx_lua's cosocket API, which ensures 100% nonblocking behavior. Note 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. Synopsis ======== ```lua # you do not need the following line if you are using # the OpenResty bundle: lua_package_path "/path/to/lua-resty-redis/lib/?.lua;;"; server { location /test { content_by_lua_block { local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec -- or connect to a unix domain socket file listened -- by a redis server: -- local ok, err = red:connect("unix:/path/to/redis.sock") local ok, err = red:connect("127.0.0.1", 6379) if not ok then ngx.say("failed to connect: ", err) return end ok, err = red:set("dog", "an animal") if not ok then ngx.say("failed to set dog: ", err) return end ngx.say("set result: ", ok) local res, err = red:get("dog") if not res then ngx.say("failed to get dog: ", err) return end if res == ngx.null then ngx.say("dog not found.") return end ngx.say("dog: ", res) red:init_pipeline() red:set("cat", "Marry") red:set("horse", "Bob") red:get("cat") red:get("horse") local results, err = red:commit_pipeline() if not results then ngx.say("failed to commit the pipelined requests: ", err) return end for i, res in ipairs(results) do if type(res) == "table" then if res[1] == false then ngx.say("failed to run command ", i, ": ", res[2]) else -- process the table value end else -- process the scalar value end end -- put it into the connection pool of size 100, -- with 10 seconds max idle time local ok, err = red:set_keepalive(10000, 100) if not ok then ngx.say("failed to set keepalive: ", err) return end -- or just close the connection right away: -- local ok, err = red:close() -- if not ok then -- ngx.say("failed to close: ", err) -- return -- end } } } ``` [Back to TOC](#table-of-contents) Methods ======= All of the Redis commands have their own methods with the same name except all in lower case. You can find the complete list of Redis commands here: http://redis.io/commands You need to check out this Redis command reference to see what Redis command accepts what arguments. The 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: ```lua local res, err = red:get("key") ``` Similarly, the "LRANGE" redis command accepts threee arguments, then you should call the "lrange" method like this: ```lua local res, err = red:lrange("nokey", 0, 1) ``` For example, "SET", "GET", "LRANGE", and "BLPOP" commands correspond to the methods "set", "get", "lrange", and "blpop". Here are some more examples: ```lua -- HMGET myhash field1 field2 nofield local res, err = red:hmget("myhash", "field1", "field2", "nofield") ``` ```lua -- HMSET myhash field1 "Hello" field2 "World" local res, err = red:hmset("myhash", "field1", "Hello", "field2", "World") ``` All 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. A Redis "status reply" results in a string typed return value with the "+" prefix stripped. A Redis "integer reply" results in a Lua number typed return value. A Redis "error reply" results in a `false` value *and* a string describing the error. A 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. A 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}`. A nil multi-bulk reply returns in a `ngx.null` value. See http://redis.io/topics/protocol for details regarding various Redis reply types. In addition to all those redis command methods, the following methods are also provided: [Back to TOC](#table-of-contents) new --- `syntax: red, err = redis:new()` Creates a redis object. In case of failures, returns `nil` and a string describing the error. [Back to TOC](#table-of-contents) connect ------- `syntax: ok, err = red:connect(host, port, options_table?)` `syntax: ok, err = red:connect("unix:/path/to/unix.sock", options_table?)` Attempts 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. Before 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. An optional Lua table can be specified as the last argument to this method to specify various connect options: * `pool` Specifies a custom name for the connection pool being used. If omitted, then the connection pool name will be generated from the string template `:` or ``. [Back to TOC](#table-of-contents) set_timeout ---------- `syntax: red:set_timeout(time)` Sets the timeout (in ms) protection for subsequent operations, including the `connect` method. [Back to TOC](#table-of-contents) set_keepalive ------------ `syntax: ok, err = red:set_keepalive(max_idle_timeout, pool_size)` Puts the current Redis connection immediately into the ngx_lua cosocket connection pool. You 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. In case of success, returns `1`. In case of errors, returns `nil` with a string describing the error. Only 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. [Back to TOC](#table-of-contents) get_reused_times ---------------- `syntax: times, err = red:get_reused_times()` This method returns the (successfully) reused times for the current connection. In case of error, it returns `nil` and a string describing the error. If 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. [Back to TOC](#table-of-contents) close ----- `syntax: ok, err = red:close()` Closes the current redis connection and returns the status. In case of success, returns `1`. In case of errors, returns `nil` with a string describing the error. [Back to TOC](#table-of-contents) init_pipeline ------------- `syntax: red:init_pipeline()` `syntax: red:init_pipeline(n)` Enable 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. This method always succeeds. If the redis object is already in the Redis pipelining mode, then calling this method will discard existing cached Redis queries. The optional `n` argument specifies the (approximate) number of commands that are going to add to this pipeline, which can make things a little faster. [Back to TOC](#table-of-contents) commit_pipeline --------------- `syntax: results, err = red:commit_pipeline()` Quits 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. This method returns `nil` and a Lua string describing the error upon failures. [Back to TOC](#table-of-contents) cancel_pipeline --------------- `syntax: red:cancel_pipeline()` Quits the pipelining mode by discarding all existing cached Redis commands since the last call to the `init_pipeline` method. This method always succeeds. If the redis object is not in the Redis pipelining mode, then this method is a no-op. [Back to TOC](#table-of-contents) hmset ----- `syntax: red:hmset(myhash, field1, value1, field2, value2, ...)` `syntax: red:hmset(myhash, { field1 = value1, field2 = value2, ... })` Special wrapper for the Redis "hmset" command. When there are only three arguments (including the "red" object itself), then the last argument must be a Lua table holding all the field/value pairs. [Back to TOC](#table-of-contents) array_to_hash ------------- `syntax: hash = red:array_to_hash(array)` Auxiliary function that converts an array-like Lua table into a hash-like table. This method was first introduced in the `v0.11` release. [Back to TOC](#table-of-contents) read_reply ---------- `syntax: res, err = red:read_reply()` Reading a reply from the redis server. This method is mostly useful for the [Redis Pub/Sub API](http://redis.io/topics/pubsub/), for example, ```lua local cjson = require "cjson" local redis = require "resty.redis" local red = redis:new() local red2 = redis:new() red:set_timeout(1000) -- 1 sec red2:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", 6379) if not ok then ngx.say("1: failed to connect: ", err) return end ok, err = red2:connect("127.0.0.1", 6379) if not ok then ngx.say("2: failed to connect: ", err) return end local res, err = red:subscribe("dog") if not res then ngx.say("1: failed to subscribe: ", err) return end ngx.say("1: subscribe: ", cjson.encode(res)) res, err = red2:publish("dog", "Hello") if not res then ngx.say("2: failed to publish: ", err) return end ngx.say("2: publish: ", cjson.encode(res)) res, err = red:read_reply() if not res then ngx.say("1: failed to read reply: ", err) return end ngx.say("1: receive: ", cjson.encode(res)) red:close() red2:close() ``` Running this example gives the output like this: 1: subscribe: ["subscribe","dog",1] 2: publish: 1 1: receive: ["message","dog","Hello"] The following class methods are provieded: [Back to TOC](#table-of-contents) add_commands ------------ `syntax: hash = redis.add_commands(cmd_name1, cmd_name2, ...)` *WARNING* this method is now deprecated since we already do automatic Lua method generation for any redis commands the user attempts to use and thus we no longer need this. Adds new redis commands to the `resty.redis` class. Here is an example: ```lua local redis = require "resty.redis" redis.add_commands("foo", "bar") local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", 6379) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:foo("a") if not res then ngx.say("failed to foo: ", err) end res, err = red:bar() if not res then ngx.say("failed to bar: ", err) end ``` [Back to TOC](#table-of-contents) Redis Authentication ==================== Redis uses the `AUTH` command to do authentication: http://redis.io/commands/auth There is nothing special for this command as compared to other Redis commands like `GET` and `SET`. So one can just invoke the `auth` method on your `resty.redis` instance. Here is an example: ```lua local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", 6379) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:auth("foobared") if not res then ngx.say("failed to authenticate: ", err) return end ``` where we assume that the Redis server is configured with the password `foobared` in the `redis.conf` file: requirepass foobared If the password specified is wrong, then the sample above will output the following to the HTTP client: failed to authenticate: ERR invalid password [Back to TOC](#table-of-contents) Redis Transactions ================== This library supports the [Redis transactions](http://redis.io/topics/transactions/). Here is an example: ```lua local cjson = require "cjson" local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", 6379) if not ok then ngx.say("failed to connect: ", err) return end local ok, err = red:multi() if not ok then ngx.say("failed to run multi: ", err) return end ngx.say("multi ans: ", cjson.encode(ok)) local ans, err = red:set("a", "abc") if not ans then ngx.say("failed to run sort: ", err) return end ngx.say("set ans: ", cjson.encode(ans)) local ans, err = red:lpop("a") if not ans then ngx.say("failed to run sort: ", err) return end ngx.say("set ans: ", cjson.encode(ans)) ans, err = red:exec() ngx.say("exec ans: ", cjson.encode(ans)) red:close() ``` Then the output will be multi ans: "OK" set ans: "QUEUED" set ans: "QUEUED" exec ans: ["OK",[false,"ERR Operation against a key holding the wrong kind of value"]] [Back to TOC](#table-of-contents) Load Balancing and Failover =========================== You 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 Similarly, you can implement automatic failover logic in Lua at great flexibility. [Back to TOC](#table-of-contents) Debugging ========= It 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, ```lua local cjson = require "cjson" ... local res, err = red:mget("h1234", "h5678") if res then print("res: ", cjson.encode(res)) end ``` [Back to TOC](#table-of-contents) Automatic Error Logging ======================= By default the underlying [ngx_lua](https://github.com/openresty/lua-nginx-module/#readme) module does error logging when socket errors happen. If you are already doing proper error handling 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, ```nginx lua_socket_log_errors off; ``` [Back to TOC](#table-of-contents) Check List for Issues ===================== 1. Ensure you configure the connection pool size properly in the [set_keepalive](#set_keepalive) . Basically if your NGINX handle `n` concurrent requests and your NGINX has `m` workers, then the connection pool size should be configured as `n/m`. For example, if your NGINX usually handles 1000 concurrent requests and you have 10 NGINX workers, then the connection pool size should be 100. 2. 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`. 3. Ensure you are not using too short timeout setting in the [set_timeout](#set_timeout) method. 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). 4. 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. 5. 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. 6. 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. [Back to TOC](#table-of-contents) Limitations =========== * This library cannot be used in code contexts like init_by_lua*, set_by_lua*, log_by_lua*, and header_filter_by_lua* where the ngx_lua cosocket API is not available. * The `resty.redis` object instance cannot be stored in a Lua variable at the Lua module level, because it will then be shared by all the concurrent requests handled by the same nginx worker process (see https://github.com/openresty/lua-nginx-module/#data-sharing-within-an-nginx-worker ) and result in bad race conditions when concurrent requests are trying to use the same `resty.redis` instance (you would see the "bad request" or "socket busy" error to be returned from the method calls). You should always initiate `resty.redis` objects in function local variables or in the `ngx.ctx` table. These places all have their own data copies for each request. [Back to TOC](#table-of-contents) Installation ============ If you are using the OpenResty bundle (http://openresty.org ), then you do not need to do anything because it already includes and enables lua-resty-redis by default. And you can just use it in your Lua code, as in ```lua local redis = require "resty.redis" ... ``` If you are using your own nginx + ngx_lua build, then you need to configure the lua_package_path directive to add the path of your lua-resty-redis source tree to ngx_lua's LUA_PATH search path, as in ```nginx # nginx.conf http { lua_package_path "/path/to/lua-resty-redis/lib/?.lua;;"; ... } ``` Ensure that the system account running your Nginx ''worker'' proceses have enough permission to read the `.lua` file. [Back to TOC](#table-of-contents) TODO ==== [Back to TOC](#table-of-contents) Community ========= [Back to TOC](#table-of-contents) English Mailing List -------------------- The [openresty-en](https://groups.google.com/group/openresty-en) mailing list is for English speakers. [Back to TOC](#table-of-contents) Chinese Mailing List -------------------- The [openresty](https://groups.google.com/group/openresty) mailing list is for Chinese speakers. [Back to TOC](#table-of-contents) Bugs and Patches ================ Please report bugs or submit patches by 1. creating a ticket on the [GitHub Issue Tracker](http://github.com/agentzh/lua-resty-redis/issues), 1. or posting to the [OpenResty community](#community). [Back to TOC](#table-of-contents) Author ====== Yichun "agentzh" Zhang (章亦春) , OpenResty Inc. [Back to TOC](#table-of-contents) Copyright and License ===================== This module is licensed under the BSD license. Copyright (C) 2012-2017, by Yichun Zhang (agentzh) , 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: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. 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. [Back to TOC](#table-of-contents) See Also ======== * the ngx_lua module: https://github.com/openresty/lua-nginx-module/#readme * the redis wired protocol specification: http://redis.io/topics/protocol * the [lua-resty-memcached](https://github.com/agentzh/lua-resty-memcached) library * the [lua-resty-mysql](https://github.com/agentzh/lua-resty-mysql) library [Back to TOC](#table-of-contents) lua-resty-redis-0.27/dist.ini000066400000000000000000000004241343021501100161250ustar00rootroot00000000000000name=lua-resty-redis abstract=Lua redis client driver for the ngx_lua based on the cosocket API author=Yichun "agentzh" Zhang (agentzh) is_original=yes license=2bsd lib_dir=lib doc_dir=lib repo_link=https://github.com/openresty/lua-resty-redis main_module=lib/resty/redis.lua lua-resty-redis-0.27/lib/000077500000000000000000000000001343021501100152275ustar00rootroot00000000000000lua-resty-redis-0.27/lib/resty/000077500000000000000000000000001343021501100163755ustar00rootroot00000000000000lua-resty-redis-0.27/lib/resty/redis.lua000066400000000000000000000220571343021501100202140ustar00rootroot00000000000000-- Copyright (C) Yichun Zhang (agentzh) local sub = string.sub local byte = string.byte local tcp = ngx.socket.tcp local null = ngx.null local type = type local pairs = pairs local unpack = unpack local setmetatable = setmetatable local tonumber = tonumber local tostring = tostring local rawget = rawget local select = select --local error = error local ok, new_tab = pcall(require, "table.new") if not ok or type(new_tab) ~= "function" then new_tab = function (narr, nrec) return {} end end local _M = new_tab(0, 54) _M._VERSION = '0.27' local common_cmds = { "get", "set", "mget", "mset", "del", "incr", "decr", -- Strings "llen", "lindex", "lpop", "lpush", "lrange", "linsert", -- Lists "hexists", "hget", "hset", "hmget", --[[ "hmset", ]] "hdel", -- Hashes "smembers", "sismember", "sadd", "srem", "sdiff", "sinter", "sunion", -- Sets "zrange", "zrangebyscore", "zrank", "zadd", "zrem", "zincrby", -- Sorted Sets "auth", "eval", "expire", "script", "sort" -- Others } local sub_commands = { "subscribe", "psubscribe" } local unsub_commands = { "unsubscribe", "punsubscribe" } local mt = { __index = _M } function _M.new(self) local sock, err = tcp() if not sock then return nil, err end return setmetatable({ _sock = sock, _subscribed = false }, mt) end function _M.set_timeout(self, timeout) local sock = rawget(self, "_sock") if not sock then error("not initialized", 2) return end return sock:settimeout(timeout) end function _M.connect(self, ...) local sock = rawget(self, "_sock") if not sock then return nil, "not initialized" end self._subscribed = false return sock:connect(...) end function _M.set_keepalive(self, ...) local sock = rawget(self, "_sock") if not sock then return nil, "not initialized" end if rawget(self, "_subscribed") then return nil, "subscribed state" end return sock:setkeepalive(...) end function _M.get_reused_times(self) local sock = rawget(self, "_sock") if not sock then return nil, "not initialized" end return sock:getreusedtimes() end local function close(self) local sock = rawget(self, "_sock") if not sock then return nil, "not initialized" end return sock:close() end _M.close = close local function _read_reply(self, sock) local line, err = sock:receive() if not line then if err == "timeout" and not rawget(self, "_subscribed") then sock:close() end return nil, err end local prefix = byte(line) if prefix == 36 then -- char '$' -- print("bulk reply") local size = tonumber(sub(line, 2)) if size < 0 then return null end local data, err = sock:receive(size) if not data then if err == "timeout" then sock:close() end return nil, err end local dummy, err = sock:receive(2) -- ignore CRLF if not dummy then return nil, err end return data elseif prefix == 43 then -- char '+' -- print("status reply") return sub(line, 2) elseif prefix == 42 then -- char '*' local n = tonumber(sub(line, 2)) -- print("multi-bulk reply: ", n) if n < 0 then return null end local vals = new_tab(n, 0) local nvals = 0 for i = 1, n do local res, err = _read_reply(self, sock) if res then nvals = nvals + 1 vals[nvals] = res elseif res == nil then return nil, err else -- be a valid redis error value nvals = nvals + 1 vals[nvals] = {false, err} end end return vals elseif prefix == 58 then -- char ':' -- print("integer reply") return tonumber(sub(line, 2)) elseif prefix == 45 then -- char '-' -- print("error reply: ", n) return false, sub(line, 2) else -- when `line` is an empty string, `prefix` will be equal to nil. return nil, "unknown prefix: \"" .. tostring(prefix) .. "\"" end end local function _gen_req(args) local nargs = #args local req = new_tab(nargs * 5 + 1, 0) req[1] = "*" .. nargs .. "\r\n" local nbits = 2 for i = 1, nargs do local arg = args[i] if type(arg) ~= "string" then arg = tostring(arg) end req[nbits] = "$" req[nbits + 1] = #arg req[nbits + 2] = "\r\n" req[nbits + 3] = arg req[nbits + 4] = "\r\n" nbits = nbits + 5 end -- it is much faster to do string concatenation on the C land -- in real world (large number of strings in the Lua VM) return req end local function _do_cmd(self, ...) local args = {...} local sock = rawget(self, "_sock") if not sock then return nil, "not initialized" end local req = _gen_req(args) local reqs = rawget(self, "_reqs") if reqs then reqs[#reqs + 1] = req return end -- print("request: ", table.concat(req)) local bytes, err = sock:send(req) if not bytes then return nil, err end return _read_reply(self, sock) end local function _check_subscribed(self, res) if type(res) == "table" and (res[1] == "unsubscribe" or res[1] == "punsubscribe") and res[3] == 0 then self._subscribed = false end end function _M.read_reply(self) local sock = rawget(self, "_sock") if not sock then return nil, "not initialized" end if not rawget(self, "_subscribed") then return nil, "not subscribed" end local res, err = _read_reply(self, sock) _check_subscribed(self, res) return res, err end for i = 1, #common_cmds do local cmd = common_cmds[i] _M[cmd] = function (self, ...) return _do_cmd(self, cmd, ...) end end for i = 1, #sub_commands do local cmd = sub_commands[i] _M[cmd] = function (self, ...) self._subscribed = true return _do_cmd(self, cmd, ...) end end for i = 1, #unsub_commands do local cmd = unsub_commands[i] _M[cmd] = function (self, ...) local res, err = _do_cmd(self, cmd, ...) _check_subscribed(self, res) return res, err end end function _M.hmset(self, hashname, ...) if select('#', ...) == 1 then local t = select(1, ...) local n = 0 for k, v in pairs(t) do n = n + 2 end local array = new_tab(n, 0) local i = 0 for k, v in pairs(t) do array[i + 1] = k array[i + 2] = v i = i + 2 end -- print("key", hashname) return _do_cmd(self, "hmset", hashname, unpack(array)) end -- backwards compatibility return _do_cmd(self, "hmset", hashname, ...) end function _M.init_pipeline(self, n) self._reqs = new_tab(n or 4, 0) end function _M.cancel_pipeline(self) self._reqs = nil end function _M.commit_pipeline(self) local reqs = rawget(self, "_reqs") if not reqs then return nil, "no pipeline" end self._reqs = nil local sock = rawget(self, "_sock") if not sock then return nil, "not initialized" end local bytes, err = sock:send(reqs) if not bytes then return nil, err end local nvals = 0 local nreqs = #reqs local vals = new_tab(nreqs, 0) for i = 1, nreqs do local res, err = _read_reply(self, sock) if res then nvals = nvals + 1 vals[nvals] = res elseif res == nil then if err == "timeout" then close(self) end return nil, err else -- be a valid redis error value nvals = nvals + 1 vals[nvals] = {false, err} end end return vals end function _M.array_to_hash(self, t) local n = #t -- print("n = ", n) local h = new_tab(0, n / 2) for i = 1, n, 2 do h[t[i]] = t[i + 1] end return h end -- this method is deperate since we already do lazy method generation. function _M.add_commands(...) local cmds = {...} for i = 1, #cmds do local cmd = cmds[i] _M[cmd] = function (self, ...) return _do_cmd(self, cmd, ...) end end end setmetatable(_M, {__index = function(self, cmd) local method = function (self, ...) return _do_cmd(self, cmd, ...) end -- cache the lazily generated method in our -- module table _M[cmd] = method return method end}) return _M lua-resty-redis-0.27/t/000077500000000000000000000000001343021501100147245ustar00rootroot00000000000000lua-resty-redis-0.27/t/bugs.t000066400000000000000000000134021343021501100160510ustar00rootroot00000000000000# vim:set ft= ts=4 sw=4 et: use Test::Nginx::Socket::Lua; use Cwd qw(cwd); repeat_each(2); plan tests => repeat_each() * (3 * blocks()); my $pwd = cwd(); my $HtmlDir = html_dir; our $HttpConfig = qq{ lua_package_path "$HtmlDir/?.lua;$pwd/lib/?.lua;;"; }; $ENV{TEST_NGINX_RESOLVER} = '8.8.8.8'; $ENV{TEST_NGINX_REDIS_PORT} ||= 6379; no_long_string(); #no_diff(); log_level 'warn'; run_tests(); __DATA__ === TEST 1: github issue #108: ngx.locaiton.capture + redis.set_keepalive --- http_config eval: $::HttpConfig --- config location /r1 { default_type text/html; set $port $TEST_NGINX_REDIS_PORT; #lua_code_cache off; lua_need_request_body on; content_by_lua_file html/r1.lua; } location /r2 { default_type text/html; set $port $TEST_NGINX_REDIS_PORT; #lua_code_cache off; lua_need_request_body on; content_by_lua_file html/r2.lua; } location /anyurl { internal; proxy_pass http://127.0.0.1:$server_port/dummy; } location = /dummy { echo dummy; } --- user_files >>> r1.lua local redis = require "resty.redis" local red = redis:new() local ok, err = red:connect("127.0.0.1", ngx.var.port) if not ok then ngx.say("failed to connect: ", err) return end local ok, err = red:flushall() if not ok then ngx.say("failed to flushall: ", err) return end ok, err = red:set_keepalive() if not ok then ngx.say("failed to set keepalive: ", err) return end local http_ress = ngx.location.capture("/r2") -- 1 ngx.say("ok") >>> r2.lua local redis = require "resty.redis" local red = redis:new() local ok, err = red:connect("127.0.0.1", ngx.var.port) --2 if not ok then ngx.say("failed to connect: ", err) return end local res = ngx.location.capture("/anyurl") --3 --- request GET /r1 --- response_body ok --- no_error_log [error] === TEST 2: exit(404) after I/O (ngx_lua github issue #110 https://github.com/chaoslawful/lua-nginx-module/issues/110 --- http_config eval: $::HttpConfig --- config error_page 400 /400.html; error_page 404 /404.html; location /foo { access_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(2000) -- 2 sec -- ngx.log(ngx.ERR, "hello"); -- or connect to a unix domain socket file listened -- by a redis server: -- local ok, err = red:connect("unix:/path/to/redis.sock") local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.log(ngx.ERR, "failed to connect: ", err) return end res, err = red:set("dog", "an animal") if not res then ngx.log(ngx.ERR, "failed to set dog: ", err) return end -- ngx.say("set dog: ", res) local res, err = red:get("dog") if err then ngx.log(ngx.ERR, "failed to get dog: ", err) return end if not res then ngx.log(ngx.ERR, "dog not found.") return end -- ngx.say("dog: ", res) -- red:close() local ok, err = red:set_keepalive(0, 100) if not ok then ngx.log(ngx.ERR, "failed to set keepalive: ", err) return end ngx.exit(404) '; echo Hello; } --- user_files >>> 400.html Bad request, dear... >>> 404.html Not found, dear... --- request GET /foo --- response_body Not found, dear... --- error_code: 404 --- no_error_log [error] === TEST 3: set and get an empty string --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec -- or connect to a unix domain socket file listened -- by a redis server: -- local ok, err = red:connect("unix:/path/to/redis.sock") local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end res, err = red:set("dog", "") if not res then ngx.say("failed to set dog: ", err) return end ngx.say("set dog: ", res) for i = 1, 2 do local res, err = red:get("dog") if err then ngx.say("failed to get dog: ", err) return end if not res then ngx.say("dog not found.") return end ngx.say("dog: ", res) end red:close() '; } --- request GET /t --- response_body set dog: OK dog: dog: --- no_error_log [error] === TEST 4: ngx.exec() after red:get() --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:get("dog") if err then ngx.say("failed to get dog: ", err) return end ngx.exec("/hello") '; } location = /hello { echo hello world; } --- request GET /t --- response_body hello world --- no_error_log [error] lua-resty-redis-0.27/t/count.t000066400000000000000000000015321343021501100162420ustar00rootroot00000000000000# vim:set ft= ts=4 sw=4 et: use Test::Nginx::Socket::Lua; use Cwd qw(cwd); repeat_each(2); plan tests => repeat_each() * (3 * blocks()); my $pwd = cwd(); our $HttpConfig = qq{ lua_package_path "$pwd/lib/?.lua;;"; lua_package_cpath "/usr/local/openresty-debug/lualib/?.so;/usr/local/openresty/lualib/?.so;;"; }; $ENV{TEST_NGINX_RESOLVER} = '8.8.8.8'; $ENV{TEST_NGINX_REDIS_PORT} ||= 6379; no_long_string(); #no_diff(); run_tests(); __DATA__ === TEST 1: module size of resty.redis --- http_config eval: $::HttpConfig --- config location = /t { content_by_lua ' local redis = require "resty.redis" n = 0 for _, _ in pairs(redis) do n = n + 1 end ngx.say("size: ", n) '; } --- request GET /t --- response_body size: 54 --- no_error_log [error] lua-resty-redis-0.27/t/hmset.t000066400000000000000000000072141343021501100162350ustar00rootroot00000000000000# vim:set ft= ts=4 sw=4 et: use Test::Nginx::Socket::Lua; use Cwd qw(cwd); repeat_each(2); plan tests => repeat_each() * (3 * blocks()); my $pwd = cwd(); our $HttpConfig = qq{ lua_package_path "$pwd/lib/?.lua;;;"; lua_package_cpath "/usr/local/openresty-debug/lualib/?.so;/usr/local/openresty/lualib/?.so;;"; }; $ENV{TEST_NGINX_RESOLVER} = '8.8.8.8'; $ENV{TEST_NGINX_REDIS_PORT} ||= 6379; no_long_string(); #no_diff(); run_tests(); __DATA__ === TEST 1: hmset key-pairs --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:hmset("animals", "dog", "bark", "cat", "meow") if not res then ngx.say("failed to set animals: ", err) return end ngx.say("hmset animals: ", res) local res, err = red:hmget("animals", "dog", "cat") if not res then ngx.say("failed to get animals: ", err) return end ngx.say("hmget animals: ", res) red:close() '; } --- request GET /t --- response_body hmset animals: OK hmget animals: barkmeow --- no_error_log [error] === TEST 2: hmset lua tables --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local t = { dog = "bark", cat = "meow", cow = "moo" } local res, err = red:hmset("animals", t) if not res then ngx.say("failed to set animals: ", err) return end ngx.say("hmset animals: ", res) local res, err = red:hmget("animals", "dog", "cat", "cow") if not res then ngx.say("failed to get animals: ", err) return end ngx.say("hmget animals: ", res) red:close() '; } --- request GET /t --- response_body hmset animals: OK hmget animals: barkmeowmoo --- no_error_log [error] === TEST 3: hmset a single scalar --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:hmset("animals", "cat") if not res then ngx.say("failed to set animals: ", err) return end ngx.say("hmset animals: ", res) local res, err = red:hmget("animals", "cat") if not res then ngx.say("failed to get animals: ", err) return end ngx.say("hmget animals: ", res) red:close() '; } --- request GET /t --- response_body_like: 500 Internal Server Error --- error_code: 500 --- error_log table expected, got string lua-resty-redis-0.27/t/mock.t000066400000000000000000000027551343021501100160530ustar00rootroot00000000000000# vim:set ft= ts=4 sw=4 et: use Test::Nginx::Socket::Lua; use Cwd qw(cwd); repeat_each(2); plan tests => repeat_each() * (4 * blocks()); my $pwd = cwd(); our $HttpConfig = qq{ lua_package_path "$pwd/lib/?.lua;;"; lua_package_cpath "/usr/local/openresty-debug/lualib/?.so;/usr/local/openresty/lualib/?.so;;"; }; $ENV{TEST_NGINX_RESOLVER} = '8.8.8.8'; $ENV{TEST_NGINX_REDIS_PORT} ||= 6379; no_long_string(); #no_diff(); run_tests(); __DATA__ === TEST 1: continue using the obj when read timeout happens --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() local ok, err = red:connect("127.0.0.1", 1921); if not ok then ngx.say("failed to connect: ", err) return end red:set_timeout(100) -- 0.1 sec for i = 1, 2 do local data, err = red:get("foo") if not data then ngx.say("failed to get: ", err) else ngx.say("get: ", data); end ngx.sleep(0.1) end red:close() '; } --- request GET /t --- tcp_listen: 1921 --- tcp_query eval "*2\r \$3\r get\r \$3\r foo\r " --- tcp_reply eval "\$5\r\nhello\r\n" --- tcp_reply_delay: 150ms --- response_body failed to get: timeout failed to get: closed --- error_log lua tcp socket read timed out lua-resty-redis-0.27/t/pipeline.t000066400000000000000000000200551343021501100167200ustar00rootroot00000000000000# vim:set ft= ts=4 sw=4 et: use Test::Nginx::Socket::Lua; use Cwd qw(cwd); repeat_each(2); plan tests => repeat_each() * (3 * blocks()); my $pwd = cwd(); our $HttpConfig = qq{ lua_package_path "$pwd/lib/?.lua;;;"; lua_package_cpath "/usr/local/openresty-debug/lualib/?.so;/usr/local/openresty/lualib/?.so;;"; }; $ENV{TEST_NGINX_RESOLVER} = '8.8.8.8'; $ENV{TEST_NGINX_REDIS_PORT} ||= 6379; no_long_string(); #no_diff(); run_tests(); __DATA__ === TEST 1: basic --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end for i = 1, 2 do red:init_pipeline() red:set("dog", "an animal") red:get("dog") red:set("dog", "hello") red:get("dog") local results = red:commit_pipeline() local cjson = require "cjson" ngx.say(cjson.encode(results)) end red:close() '; } --- request GET /t --- response_body ["OK","an animal","OK","hello"] ["OK","an animal","OK","hello"] --- no_error_log [error] === TEST 2: cancel automatically --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end red:init_pipeline() red:set("dog", "an animal") red:get("dog") for i = 1, 2 do red:init_pipeline() red:set("dog", "an animal") red:get("dog") red:set("dog", "hello") red:get("dog") local results = red:commit_pipeline() local cjson = require "cjson" ngx.say(cjson.encode(results)) end red:close() '; } --- request GET /t --- response_body ["OK","an animal","OK","hello"] ["OK","an animal","OK","hello"] --- no_error_log [error] === TEST 3: cancel explicitly --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end red:init_pipeline() red:set("dog", "an animal") red:get("dog") red:cancel_pipeline() local res, err = red:flushall() if not res then ngx.say("failed to flush all: ", err) return end ngx.say("flushall: ", res) for i = 1, 2 do red:init_pipeline() red:set("dog", "an animal") red:get("dog") red:set("dog", "hello") red:get("dog") local results = red:commit_pipeline() local cjson = require "cjson" ngx.say(cjson.encode(results)) end red:close() '; } --- request GET /t --- response_body flushall: OK ["OK","an animal","OK","hello"] ["OK","an animal","OK","hello"] --- no_error_log [error] === TEST 4: mixed --- http_config eval: $::HttpConfig --- config location /test { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", 6379) if not ok then ngx.say("failed to connect: ", err) return end res, err = red:set("dog", "an aniaml") if not ok then ngx.say("failed to set dog: ", err) return end ngx.say("set result: ", res) local res, err = red:get("dog") if not res then ngx.say("failed to get dog: ", err) return end if res == ngx.null then ngx.say("dog not found.") return end ngx.say("dog: ", res) red:init_pipeline() red:set("cat", "Marry") red:set("horse", "Bob") red:get("cat") red:get("horse") local results, err = red:commit_pipeline() if not results then ngx.say("failed to commit the pipelined requests: ", err) return end for i, res in ipairs(results) do if type(res) == "table" then if res[1] == false then ngx.say("failed to run command ", i, ": ", res[2]) else ngx.say("cmd ", i, ": ", res) end else -- process the scalar value ngx.say("cmd ", i, ": ", res) end end -- put it into the connection pool of size 100, -- with 0 idle timeout local ok, err = red:set_keepalive(0, 100) if not ok then ngx.say("failed to set keepalive: ", err) return end -- or just close the connection right away: -- local ok, err = red:close() -- if not ok then -- ngx.say("failed to close: ", err) -- return -- end '; } --- request GET /test --- response_body set result: OK dog: an aniaml cmd 1: OK cmd 2: OK cmd 3: Marry cmd 4: Bob --- no_error_log [error] === TEST 5: redis return error in pipeline --- http_config eval: $::HttpConfig --- config location /test { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", 6379) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:del("dog") if not res then ngx.say("failed to del dog: ", err) return end red:init_pipeline() red:hkeys("dog") red:set("dog", "an animal") red:hkeys("dog") red:get("dog") local results, err = red:commit_pipeline() if not results then ngx.say("failed to commit the pipelined requests: ", err) return end for i, res in ipairs(results) do if type(res) == "table" then if res[1] == false then ngx.say("failed to run command ", i, ": ", res[2]) else ngx.say("cmd ", i, ": ", res) end else -- process the scalar value ngx.say("cmd ", i, ": ", res) end end -- put it into the connection pool of size 100, -- with 0 idle timeout local ok, err = red:set_keepalive(0, 100) if not ok then ngx.say("failed to set keepalive: ", err) return end '; } --- request GET /test --- response_body cmd 1: cmd 2: OK failed to run command 3: WRONGTYPE Operation against a key holding the wrong kind of value cmd 4: an animal --- no_error_log [error] lua-resty-redis-0.27/t/pubsub.t000066400000000000000000000354221343021501100164170ustar00rootroot00000000000000# vim:set ft= ts=4 sw=4 et: use Test::Nginx::Socket::Lua; use Cwd qw(cwd); repeat_each(2); plan tests => repeat_each() * (3 * blocks()); my $pwd = cwd(); our $HttpConfig = qq{ lua_package_path "$pwd/lib/?.lua;;"; lua_package_cpath "/usr/local/openresty-debug/lualib/?.so;/usr/local/openresty/lualib/?.so;;"; }; $ENV{TEST_NGINX_RESOLVER} = '8.8.8.8'; $ENV{TEST_NGINX_REDIS_PORT} ||= 6379; no_long_string(); #no_diff(); run_tests(); __DATA__ === TEST 1: single channel --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local cjson = require "cjson" local redis = require "resty.redis" local red = redis:new() local red2 = redis:new() red:set_timeout(1000) -- 1 sec red2:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("1: failed to connect: ", err) return end ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("2: failed to connect: ", err) return end res, err = red:subscribe("dog") if not res then ngx.say("1: failed to subscribe: ", err) return end ngx.say("1: subscribe: ", cjson.encode(res)) res, err = red2:publish("dog", "Hello") if not res then ngx.say("2: failed to publish: ", err) return end ngx.say("2: publish: ", cjson.encode(res)) res, err = red:read_reply() if not res then ngx.say("1: failed to read reply: ", err) return end ngx.say("1: receive: ", cjson.encode(res)) red:close() red2:close() '; } --- request GET /t --- response_body 1: subscribe: ["subscribe","dog",1] 2: publish: 1 1: receive: ["message","dog","Hello"] --- no_error_log [error] === TEST 2: single channel (retry read_reply() after timeout) --- http_config eval: $::HttpConfig --- config lua_socket_log_errors off; location /t { content_by_lua ' local cjson = require "cjson" local redis = require "resty.redis" local red = redis:new() local red2 = redis:new() red:set_timeout(1000) -- 1 sec red2:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("1: failed to connect: ", err) return end ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("2: failed to connect: ", err) return end res, err = red:subscribe("dog") if not res then ngx.say("1: failed to subscribe: ", err) return end ngx.say("1: subscribe: ", cjson.encode(res)) red:set_timeout(1) for i = 1, 2 do res, err = red:read_reply() if not res then ngx.say("1: failed to read reply: ", err) if err ~= "timeout" then return end end end red:set_timeout(1000) res, err = red:unsubscribe("dog") if not res then ngx.say("1: failed to unsubscribe: ", err) else ngx.say("1: unsubscribe: ", cjson.encode(res)) end res, err = red2:publish("dog", "Hello") if not res then ngx.say("2: failed to publish: ", err) return end ngx.say("2: publish: ", cjson.encode(res)) res, err = red:read_reply() if not res then ngx.say("1: failed to read reply: ", err) else ngx.say("1: receive: ", cjson.encode(res)) end res, err = red:unsubscribe("dog") if not res then ngx.say("1: failed to unsubscribe: ", err) return end ngx.say("1: unsubscribe: ", cjson.encode(res)) red:close() red2:close() '; } --- request GET /t --- response_body 1: subscribe: ["subscribe","dog",1] 1: failed to read reply: timeout 1: failed to read reply: timeout 1: unsubscribe: ["unsubscribe","dog",0] 2: publish: 0 1: failed to read reply: not subscribed 1: unsubscribe: ["unsubscribe","dog",0] --- no_error_log [error] === TEST 3: multiple channels --- http_config eval: $::HttpConfig --- config location /t { lua_socket_log_errors off; content_by_lua ' local cjson = require "cjson" local redis = require "resty.redis" local red = redis:new() local red2 = redis:new() red:set_timeout(1000) -- 1 sec red2:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("1: failed to connect: ", err) return end ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("2: failed to connect: ", err) return end res, err = red:subscribe("dog") if not res then ngx.say("1: failed to subscribe: ", err) return end ngx.say("1: subscribe dog: ", cjson.encode(res)) res, err = red:subscribe("cat") if not res then ngx.say("1: failed to subscribe: ", err) return end ngx.say("1: subscribe cat: ", cjson.encode(res)) res, err = red2:publish("dog", "Hello") if not res then ngx.say("2: failed to publish: ", err) return end ngx.say("2: publish: ", cjson.encode(res)) res, err = red:read_reply() if not res then ngx.say("1: failed to read reply: ", err) else ngx.say("1: receive: ", cjson.encode(res)) end red:set_timeout(10) -- 10ms res, err = red:read_reply() if not res then ngx.say("1: failed to read reply: ", err) else ngx.say("1: receive: ", cjson.encode(res)) end red:set_timeout(1000) -- 1s res, err = red:unsubscribe() if not res then ngx.say("1: failed to unscribe: ", err) else ngx.say("1: unsubscribe: ", cjson.encode(res)) end res, err = red:read_reply() if not res then ngx.say("1: failed to read reply: ", err) else ngx.say("1: receive: ", cjson.encode(res)) end red:set_timeout(10) -- 10ms res, err = red:read_reply() if not res then ngx.say("1: failed to read reply: ", err) else ngx.say("1: receive: ", cjson.encode(res)) end red:set_timeout(1000) -- 1s red:close() red2:close() '; } --- request GET /t --- response_body_like chop ^1: subscribe dog: \["subscribe","dog",1\] 1: subscribe cat: \["subscribe","cat",2\] 2: publish: 1 1: receive: \["message","dog","Hello"\] 1: failed to read reply: timeout 1: unsubscribe: \["unsubscribe","(?:cat|dog)",1\] 1: receive: \["unsubscribe","(?:dog|cat)",0\] 1: failed to read reply: not subscribed$ --- no_error_log [error] === TEST 4: call subscribe after read_reply() times out --- http_config eval: $::HttpConfig --- config lua_socket_log_errors off; location /t { content_by_lua ' local cjson = require "cjson" local redis = require "resty.redis" local red = redis:new() local red2 = redis:new() red:set_timeout(1000) -- 1 sec red2:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("1: failed to connect: ", err) return end ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("2: failed to connect: ", err) return end res, err = red:subscribe("dog") if not res then ngx.say("1: failed to subscribe: ", err) return end ngx.say("1: subscribe: ", cjson.encode(res)) red:set_timeout(1) for i = 1, 2 do res, err = red:read_reply() if not res then ngx.say("1: failed to read reply: ", err) if err ~= "timeout" then return end end end red:set_timeout(1000) res, err = red:subscribe("cat") if not res then ngx.say("1: failed to subscribe to cat: ", err) else ngx.say("1: subscribe: ", cjson.encode(res)) end red:close() red2:close() '; } --- request GET /t --- response_body 1: subscribe: ["subscribe","dog",1] 1: failed to read reply: timeout 1: failed to read reply: timeout 1: subscribe: ["subscribe","cat",2] --- no_error_log [error] === TEST 5: call set_keepalive in subscribed mode (previous read_reply calls timed out) --- http_config eval: $::HttpConfig --- config lua_socket_log_errors off; location /t { content_by_lua ' local cjson = require "cjson" local redis = require "resty.redis" local red = redis:new() local red2 = redis:new() red:set_timeout(1000) -- 1 sec red2:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("1: failed to connect: ", err) return end ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("2: failed to connect: ", err) return end res, err = red:subscribe("dog") if not res then ngx.say("1: failed to subscribe: ", err) return end ngx.say("1: subscribe: ", cjson.encode(res)) red:set_timeout(1) for i = 1, 2 do res, err = red:read_reply() if not res then ngx.say("1: failed to read reply: ", err) if err ~= "timeout" then return end end end red:set_timeout(1000) res, err = red:set_keepalive() if not res then ngx.say("1: failed to set keepalive: ", err) else ngx.say("1: set keepalive: ", cjson.encode(res)) end red:close() red2:close() '; } --- request GET /t --- response_body 1: subscribe: ["subscribe","dog",1] 1: failed to read reply: timeout 1: failed to read reply: timeout 1: failed to set keepalive: subscribed state --- no_error_log [error] === TEST 6: call set_keepalive in subscribed mode --- http_config eval: $::HttpConfig --- config lua_socket_log_errors off; location /t { content_by_lua ' local cjson = require "cjson" local redis = require "resty.redis" local red = redis:new() local red2 = redis:new() red:set_timeout(1000) -- 1 sec red2:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("1: failed to connect: ", err) return end ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("2: failed to connect: ", err) return end res, err = red:subscribe("dog") if not res then ngx.say("1: failed to subscribe: ", err) return end ngx.say("1: subscribe: ", cjson.encode(res)) res, err = red:set_keepalive() if not res then ngx.say("1: failed to set keepalive: ", err) else ngx.say("1: set keepalive: ", cjson.encode(res)) end red:close() red2:close() '; } --- request GET /t --- response_body 1: subscribe: ["subscribe","dog",1] 1: failed to set keepalive: subscribed state --- no_error_log [error] === TEST 7: call set_keepalive in unsubscribed mode --- http_config eval: $::HttpConfig --- config lua_socket_log_errors off; location /t { content_by_lua ' local cjson = require "cjson" local redis = require "resty.redis" local red = redis:new() local red2 = redis:new() red:set_timeout(1000) -- 1 sec red2:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("1: failed to connect: ", err) return end ok, err = red2:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("2: failed to connect: ", err) return end res, err = red:subscribe("dog") if not res then ngx.say("1: failed to subscribe: ", err) return end ngx.say("1: subscribe: ", cjson.encode(res)) res, err = red:unsubscribe() if not res then ngx.say("1: failed to unsubscribe: ", err) return end ngx.say("1: unsubscribe: ", cjson.encode(res)) res, err = red:set_keepalive() if not res then ngx.say("1: failed to set keepalive: ", err) else ngx.say("1: set keepalive: ", cjson.encode(res)) end red:close() red2:close() '; } --- request GET /t --- response_body 1: subscribe: ["subscribe","dog",1] 1: unsubscribe: ["unsubscribe","dog",0] 1: set keepalive: 1 --- no_error_log [error] lua-resty-redis-0.27/t/sanity.t000066400000000000000000000501441343021501100164240ustar00rootroot00000000000000# vim:set ft= ts=4 sw=4 et: use Test::Nginx::Socket::Lua; use Cwd qw(cwd); repeat_each(2); plan tests => repeat_each() * (3 * blocks()); my $pwd = cwd(); our $HttpConfig = qq{ lua_package_path "$pwd/lib/?.lua;;"; lua_package_cpath "/usr/local/openresty-debug/lualib/?.so;/usr/local/openresty/lualib/?.so;;"; }; $ENV{TEST_NGINX_RESOLVER} = '8.8.8.8'; $ENV{TEST_NGINX_REDIS_PORT} ||= 6379; no_long_string(); #no_diff(); run_tests(); __DATA__ === TEST 1: set and get --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end ok, err = red:select(1) if not ok then ngx.say("failed to select: ", err) return end local res, err = red:set("dog", "an animal") if not res then ngx.say("failed to set dog: ", err) return end ngx.say("set dog: ", res) for i = 1, 2 do local res, err = red:get("dog") if err then ngx.say("failed to get dog: ", err) return end if not res then ngx.say("dog not found.") return end ngx.say("dog: ", res) end red:close() '; } --- request GET /t --- response_body set dog: OK dog: an animal dog: an animal --- no_error_log [error] === TEST 2: flushall --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:flushall() if not res then ngx.say("failed to flushall: ", err) return end ngx.say("flushall: ", res) red:close() '; } --- request GET /t --- response_body flushall: OK --- no_error_log [error] === TEST 3: get nil bulk value --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:flushall() if not res then ngx.say("failed to flushall: ", err) return end ngx.say("flushall: ", res) for i = 1, 2 do res, err = red:get("not_found") if err then ngx.say("failed to get: ", err) return end if res == ngx.null then ngx.say("not_found not found.") return end ngx.say("get not_found: ", res) end red:close() '; } --- request GET /t --- response_body flushall: OK not_found not found. --- no_error_log [error] === TEST 4: get nil list --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:flushall() if not res then ngx.say("failed to flushall: ", err) return end ngx.say("flushall: ", res) for i = 1, 2 do res, err = red:lrange("nokey", 0, 1) if err then ngx.say("failed to get: ", err) return end if res == ngx.null then ngx.say("nokey not found.") return end ngx.say("get nokey: ", #res, " (", type(res), ")") end red:close() '; } --- request GET /t --- response_body flushall: OK get nokey: 0 (table) get nokey: 0 (table) --- no_error_log [error] === TEST 5: incr and decr --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:set("connections", 10) if not res then ngx.say("failed to set connections: ", err) return end ngx.say("set connections: ", res) res, err = red:incr("connections") if not res then ngx.say("failed to set connections: ", err) return end ngx.say("incr connections: ", res) local res, err = red:get("connections") if err then ngx.say("failed to get connections: ", err) return end res, err = red:incr("connections") if not res then ngx.say("failed to incr connections: ", err) return end ngx.say("incr connections: ", res) res, err = red:decr("connections") if not res then ngx.say("failed to decr connections: ", err) return end ngx.say("decr connections: ", res) res, err = red:get("connections") if not res then ngx.say("connections not found.") return end ngx.say("connections: ", res) res, err = red:del("connections") if not res then ngx.say("failed to del connections: ", err) return end ngx.say("del connections: ", res) res, err = red:incr("connections") if not res then ngx.say("failed to set connections: ", err) return end ngx.say("incr connections: ", res) res, err = red:get("connections") if not res then ngx.say("connections not found.") return end ngx.say("connections: ", res) red:close() '; } --- request GET /t --- response_body set connections: OK incr connections: 11 incr connections: 12 decr connections: 11 connections: 11 del connections: 1 incr connections: 1 connections: 1 --- no_error_log [error] === TEST 6: bad incr command format --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:incr("connections", 12) if not res then ngx.say("failed to set connections: ", res, ": ", err) return end ngx.say("incr connections: ", res) red:close() '; } --- request GET /t --- response_body failed to set connections: false: ERR wrong number of arguments for 'incr' command --- no_error_log [error] === TEST 7: lpush and lrange --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:flushall() if not res then ngx.say("failed to flushall: ", err) return end ngx.say("flushall: ", res) local res, err = red:lpush("mylist", "world") if not res then ngx.say("failed to lpush: ", err) return end ngx.say("lpush result: ", res) res, err = red:lpush("mylist", "hello") if not res then ngx.say("failed to lpush: ", err) return end ngx.say("lpush result: ", res) res, err = red:lrange("mylist", 0, -1) if not res then ngx.say("failed to lrange: ", err) return end local cjson = require "cjson" ngx.say("lrange result: ", cjson.encode(res)) red:close() '; } --- request GET /t --- response_body flushall: OK lpush result: 1 lpush result: 2 lrange result: ["hello","world"] --- no_error_log [error] === TEST 8: blpop expires its own timeout --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(2500) -- 2.5 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:flushall() if not res then ngx.say("failed to flushall: ", err) return end ngx.say("flushall: ", res) local res, err = red:blpop("key", 1) if err then ngx.say("failed to blpop: ", err) return end if res == ngx.null then ngx.say("no element popped.") return end local cjson = require "cjson" ngx.say("blpop result: ", cjson.encode(res)) red:close() '; } --- request GET /t --- response_body flushall: OK no element popped. --- no_error_log [error] --- timeout: 3 === TEST 9: blpop expires cosocket timeout --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:flushall() if not res then ngx.say("failed to flushall: ", err) return end ngx.say("flushall: ", res) red:set_timeout(200) -- 200 ms local res, err = red:blpop("key", 1) if err then ngx.say("failed to blpop: ", err) return end if not res then ngx.say("no element popped.") return end local cjson = require "cjson" ngx.say("blpop result: ", cjson.encode(res)) red:close() '; } --- request GET /t --- response_body flushall: OK failed to blpop: timeout --- error_log lua tcp socket read timed out === TEST 10: set keepalive and get reused times --- http_config eval: $::HttpConfig --- config resolver $TEST_NGINX_RESOLVER; location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local times = red:get_reused_times() ngx.say("reused times: ", times) local ok, err = red:set_keepalive() if not ok then ngx.say("failed to set keepalive: ", err) return end ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end times = red:get_reused_times() ngx.say("reused times: ", times) '; } --- request GET /t --- response_body reused times: 0 reused times: 1 --- no_error_log [error] === TEST 11: mget --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end ok, err = red:flushall() if not ok then ngx.say("failed to flush all: ", err) return end local res, err = red:set("dog", "an animal") if not res then ngx.say("failed to set dog: ", err) return end ngx.say("set dog: ", res) for i = 1, 2 do local res, err = red:mget("dog", "cat", "dog") if err then ngx.say("failed to get dog: ", err) return end if not res then ngx.say("dog not found.") return end local cjson = require "cjson" ngx.say("res: ", cjson.encode(res)) end red:close() '; } --- request GET /t --- response_body set dog: OK res: ["an animal",null,"an animal"] res: ["an animal",null,"an animal"] --- no_error_log [error] === TEST 12: hmget array_to_hash --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end ok, err = red:flushall() if not ok then ngx.say("failed to flush all: ", err) return end local res, err = red:hmset("animals", { dog = "bark", cat = "meow", cow = "moo" }) if not res then ngx.say("failed to set animals: ", err) return end ngx.say("hmset animals: ", res) local res, err = red:hmget("animals", "dog", "cat", "cow") if not res then ngx.say("failed to get animals: ", err) return end ngx.say("hmget animals: ", res) local res, err = red:hgetall("animals") if err then ngx.say("failed to get animals: ", err) return end if not res then ngx.say("animals not found.") return end local h = red:array_to_hash(res) ngx.say("dog: ", h.dog) ngx.say("cat: ", h.cat) ngx.say("cow: ", h.cow) red:close() '; } --- request GET /t --- response_body hmset animals: OK hmget animals: barkmeowmoo dog: bark cat: meow cow: moo --- no_error_log [error] === TEST 13: boolean args --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end ok, err = red:set("foo", true) if not ok then ngx.say("failed to set: ", err) return end local res, err = red:get("foo") if not res then ngx.say("failed to get: ", err) return end ngx.say("foo: ", res, ", type: ", type(res)) ok, err = red:set("foo", false) if not ok then ngx.say("failed to set: ", err) return end local res, err = red:get("foo") if not res then ngx.say("failed to get: ", err) return end ngx.say("foo: ", res, ", type: ", type(res)) ok, err = red:set("foo", nil) if not ok then ngx.say("failed to set: ", err) end local res, err = red:get("foo") if not res then ngx.say("failed to get: ", err) return end ngx.say("foo: ", res, ", type: ", type(res)) local ok, err = red:set_keepalive(10, 10) if not ok then ngx.say("failed to set_keepalive: ", err) end '; } --- request GET /t --- response_body foo: true, type: string foo: false, type: string failed to set: ERR wrong number of arguments for 'set' command foo: false, type: string --- no_error_log [error] === TEST 14: set and get (key with underscores) --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:set("a_dog", "an animal") if not res then ngx.say("failed to set a_dog: ", err) return end ngx.say("set a_dog: ", res) for i = 1, 2 do local res, err = red:get("a_dog") if err then ngx.say("failed to get a_dog: ", err) return end if not res then ngx.say("a_dog not found.") return end ngx.say("a_dog: ", res) end red:close() '; } --- request GET /t --- response_body set a_dog: OK a_dog: an animal a_dog: an animal --- no_error_log [error] === TEST 15: connection refused --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" local red = redis:new() red:set_timeout(10000) -- 10 sec local ok, err = red:connect("127.0.0.1", 81) if not ok then ngx.say("failed to connect: ", err) return end ngx.say("connected") red:close() '; } --- request GET /t --- response_body failed to connect: connection refused --- timeout: 3 --- no_error_log [alert] lua-resty-redis-0.27/t/transaction.t000066400000000000000000000065271343021501100174500ustar00rootroot00000000000000# vim:set ft= ts=4 sw=4 et: use Test::Nginx::Socket::Lua; use Cwd qw(cwd); repeat_each(2); plan tests => repeat_each() * (3 * blocks()); my $pwd = cwd(); our $HttpConfig = qq{ lua_package_path "$pwd/lib/?.lua;;"; lua_package_cpath "/usr/local/openresty-debug/lualib/?.so;/usr/local/openresty/lualib/?.so;;"; }; $ENV{TEST_NGINX_RESOLVER} = '8.8.8.8'; $ENV{TEST_NGINX_REDIS_PORT} ||= 6379; no_long_string(); #no_diff(); run_tests(); __DATA__ === TEST 1: sanity --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local cjson = require "cjson" local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local redis_key = "foo" local ok, err = red:multi() if not ok then ngx.say("failed to run multi: ", err) return end ngx.say("multi ans: ", cjson.encode(ok)) local ans, err = red:sort("log", "by", redis_key .. ":*->timestamp") if not ans then ngx.say("failed to run sort: ", err) return end ngx.say("sort ans: ", cjson.encode(ans)) ans, err = red:exec() ngx.say("exec ans: ", cjson.encode(ans)) local ok, err = red:set_keepalive(0, 1024) if not ok then ngx.say("failed to put the current redis connection into pool: ", err) return end '; } --- request GET /t --- response_body multi ans: "OK" sort ans: "QUEUED" exec ans: [{}] --- no_error_log [error] === TEST 2: redis cmd reference sample: redis does not halt on errors --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local cjson = require "cjson" local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local ok, err = red:multi() if not ok then ngx.say("failed to run multi: ", err) return end ngx.say("multi ans: ", cjson.encode(ok)) local ans, err = red:set("a", "abc") if not ans then ngx.say("failed to run sort: ", err) return end ngx.say("set ans: ", cjson.encode(ans)) local ans, err = red:lpop("a") if not ans then ngx.say("failed to run sort: ", err) return end ngx.say("set ans: ", cjson.encode(ans)) ans, err = red:exec() ngx.say("exec ans: ", cjson.encode(ans)) red:close() '; } --- request GET /t --- response_body_like chop ^multi ans: "OK" set ans: "QUEUED" set ans: "QUEUED" exec ans: \["OK",\[false,"(?:ERR|WRONGTYPE) Operation against a key holding the wrong kind of value"\]\] $ --- no_error_log [error] lua-resty-redis-0.27/t/user-cmds.t000066400000000000000000000027471343021501100170250ustar00rootroot00000000000000# vim:set ft= ts=4 sw=4 et: use Test::Nginx::Socket::Lua; use Cwd qw(cwd); repeat_each(2); plan tests => repeat_each() * (3 * blocks()); my $pwd = cwd(); our $HttpConfig = qq{ lua_package_path "$pwd/lib/?.lua;;"; lua_package_cpath "/usr/local/openresty-debug/lualib/?.so;/usr/local/openresty/lualib/?.so;;"; }; $ENV{TEST_NGINX_RESOLVER} = '8.8.8.8'; $ENV{TEST_NGINX_REDIS_PORT} ||= 6379; no_long_string(); #no_diff(); run_tests(); __DATA__ === TEST 1: single channel --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local cjson = require "cjson" local redis = require "resty.redis" redis.add_commands("foo", "bar") local red = redis:new() red:set_timeout(1000) -- 1 sec local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT) if not ok then ngx.say("failed to connect: ", err) return end local res, err = red:foo("a") if not res then ngx.say("failed to foo: ", err) end res, err = red:bar() if not res then ngx.say("failed to bar: ", err) end '; } --- request GET /t --- response_body eval qr/\Afailed to foo: ERR unknown command [`']foo[`'](?:, with args beginning with: `a`,\s*)? failed to bar: ERR unknown command [`']bar[`'](?:, with args beginning with:\s*)? \z/ --- no_error_log [error] lua-resty-redis-0.27/t/version.t000066400000000000000000000011511343021501100165740ustar00rootroot00000000000000# vim:set ft= ts=4 sw=4 et: use Test::Nginx::Socket::Lua; use Cwd qw(cwd); repeat_each(2); plan tests => repeat_each() * (3 * blocks()); my $pwd = cwd(); our $HttpConfig = qq{ lua_package_path "$pwd/lib/?.lua;;"; }; $ENV{TEST_NGINX_RESOLVER} = '8.8.8.8'; no_long_string(); #no_diff(); run_tests(); __DATA__ === TEST 1: basic --- http_config eval: $::HttpConfig --- config location /t { content_by_lua ' local redis = require "resty.redis" ngx.say(redis._VERSION) '; } --- request GET /t --- response_body_like chop ^\d+\.\d+$ --- no_error_log [error] lua-resty-redis-0.27/valgrind.suppress000066400000000000000000000164011343021501100200770ustar00rootroot00000000000000{ Memcheck:Param write(buf) fun:__write_nocancel fun:ngx_log_error_core fun:ngx_resolver_read_response } { Memcheck:Cond fun:ngx_sprintf_num fun:ngx_vslprintf fun:ngx_log_error_core fun:ngx_resolver_read_response fun:ngx_epoll_process_events fun:ngx_process_events_and_timers fun:ngx_single_process_cycle fun:main } { Memcheck:Addr1 fun:ngx_vslprintf fun:ngx_snprintf fun:ngx_sock_ntop fun:ngx_event_accept } { Memcheck:Param write(buf) fun:__write_nocancel fun:ngx_log_error_core fun:ngx_resolver_read_response fun:ngx_event_process_posted fun:ngx_process_events_and_timers fun:ngx_single_process_cycle fun:main } { Memcheck:Cond fun:ngx_sprintf_num fun:ngx_vslprintf fun:ngx_log_error_core fun:ngx_resolver_read_response fun:ngx_event_process_posted fun:ngx_process_events_and_timers fun:ngx_single_process_cycle fun:main } { Memcheck:Leak fun:malloc fun:ngx_alloc obj:* } { exp-sgcheck:SorG fun:ngx_http_lua_ndk_set_var_get } { exp-sgcheck:SorG fun:ngx_http_variables_init_vars fun:ngx_http_block } { exp-sgcheck:SorG fun:ngx_conf_parse } { exp-sgcheck:SorG fun:ngx_vslprintf fun:ngx_log_error_core } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_calloc fun:ngx_event_process_init } { Memcheck:Param epoll_ctl(event) fun:epoll_ctl } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_event_process_init } { Memcheck:Cond fun:ngx_conf_flush_files fun:ngx_single_process_cycle } { Memcheck:Cond fun:memcpy fun:ngx_vslprintf fun:ngx_log_error_core fun:ngx_http_charset_header_filter } { Memcheck:Param socketcall.setsockopt(optval) fun:setsockopt fun:drizzle_state_connect } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_pool_cleanup_add } { Memcheck:Cond fun:ngx_conf_flush_files fun:ngx_single_process_cycle fun:main } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_palloc_large fun:ngx_palloc fun:ngx_array_push fun:ngx_http_get_variable_index fun:ngx_http_memc_add_variable fun:ngx_http_memc_init fun:ngx_http_block fun:ngx_conf_parse fun:ngx_init_cycle fun:main } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_event_process_init fun:ngx_single_process_cycle fun:main } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_crc32_table_init fun:main } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_event_process_init fun:ngx_worker_process_init fun:ngx_worker_process_cycle fun:ngx_spawn_process fun:ngx_start_worker_processes fun:ngx_master_process_cycle fun:main } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_palloc_large fun:ngx_palloc fun:ngx_pcalloc fun:ngx_hash_init fun:ngx_http_variables_init_vars fun:ngx_http_block fun:ngx_conf_parse fun:ngx_init_cycle fun:main } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_palloc_large fun:ngx_palloc fun:ngx_pcalloc fun:ngx_http_upstream_drizzle_create_srv_conf fun:ngx_http_upstream fun:ngx_conf_parse fun:ngx_http_block fun:ngx_conf_parse fun:ngx_init_cycle fun:main } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_palloc_large fun:ngx_palloc fun:ngx_pcalloc fun:ngx_hash_keys_array_init fun:ngx_http_variables_add_core_vars fun:ngx_http_core_preconfiguration fun:ngx_http_block fun:ngx_conf_parse fun:ngx_init_cycle fun:main } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_palloc_large fun:ngx_palloc fun:ngx_array_push fun:ngx_hash_add_key fun:ngx_http_add_variable fun:ngx_http_echo_add_variables fun:ngx_http_echo_handler_init fun:ngx_http_block fun:ngx_conf_parse fun:ngx_init_cycle } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_palloc_large fun:ngx_palloc fun:ngx_pcalloc fun:ngx_http_upstream_drizzle_create_srv_conf fun:ngx_http_core_server fun:ngx_conf_parse fun:ngx_http_block fun:ngx_conf_parse fun:ngx_init_cycle fun:main } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_palloc_large fun:ngx_palloc fun:ngx_pcalloc fun:ngx_http_upstream_drizzle_create_srv_conf fun:ngx_http_block fun:ngx_conf_parse fun:ngx_init_cycle fun:main } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_palloc_large fun:ngx_palloc fun:ngx_array_push fun:ngx_hash_add_key fun:ngx_http_variables_add_core_vars fun:ngx_http_core_preconfiguration fun:ngx_http_block fun:ngx_conf_parse fun:ngx_init_cycle fun:main } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_palloc_large fun:ngx_palloc fun:ngx_pcalloc fun:ngx_init_cycle fun:main } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_palloc_large fun:ngx_palloc fun:ngx_hash_init fun:ngx_http_upstream_init_main_conf fun:ngx_http_block fun:ngx_conf_parse fun:ngx_init_cycle fun:main } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_palloc_large fun:ngx_palloc fun:ngx_pcalloc fun:ngx_http_drizzle_keepalive_init fun:ngx_http_upstream_drizzle_init fun:ngx_http_upstream_init_main_conf fun:ngx_http_block fun:ngx_conf_parse fun:ngx_init_cycle fun:main } { Memcheck:Leak fun:malloc fun:ngx_alloc fun:ngx_palloc_large fun:ngx_palloc fun:ngx_hash_init fun:ngx_http_variables_init_vars fun:ngx_http_block fun:ngx_conf_parse fun:ngx_init_cycle fun:main } { Memcheck:Cond fun:index fun:expand_dynamic_string_token fun:_dl_map_object fun:map_doit fun:_dl_catch_error fun:do_preload fun:dl_main fun:_dl_sysdep_start fun:_dl_start } { Memcheck:Leak match-leak-kinds: definite fun:malloc fun:ngx_alloc fun:ngx_set_environment fun:ngx_single_process_cycle } { Memcheck:Leak match-leak-kinds: definite fun:malloc fun:ngx_alloc fun:ngx_set_environment fun:ngx_worker_process_init fun:ngx_worker_process_cycle }