ngx_redis2 - Nginx upstream module for the Redis 2.0 protocol *This module is not distributed with the Nginx source.* See the installation instructions. STATUS This module is still under development and is considered experimental. SYNOPSIS location /foo { set $value 'first'; redis2_query set one $value; redis2_pass 127.0.0.1:6379; } # GET /get?key=some_key location /get { set_unescape_uri $key $arg_key; # this requires ngx_set_misc redis2_query get $key; redis2_pass foo.com:6379; } # GET /set?key=one&val=first%20value location /set { set_unescape_uri $key $arg_key; # this requires ngx_set_misc set_unescape_uri $val $arg_val; # this requires ngx_set_misc redis2_query set $key $val; redis2_pass foo.com:6379; } # multiple pipelined queries location /foo { set $value 'first'; redis2_query set one $value; redis2_query get one; redis2_query set one two; redis2_query get one; redis2_pass 127.0.0.1:6379; } location /bar { # $ is not special here... redis2_literal_raw_query '*1\r\n$4\r\nping\r\n'; redis2_pass 127.0.0.1:6379; } location /bar { # variables can be used below and $ is special redis2_raw_query 'get one\r\n'; redis2_pass 127.0.0.1:6379; } # GET /baz?get%20foo%0d%0a location /baz { set_unescape_uri $query $query_string; # this requires the ngx_set_misc module redis2_raw_query $query; redis2_pass 127.0.0.1:6379; } Description This is an nginx upstream module that makes nginx talk to a redis 2.x server in a non-blocking way. The full Redis 2.0 unified protocol has been implemented including the redis pipelining support. This module returns the raw TCP response from the redis server. It's recommended to use my lua-redis-parser module (written in pure C) to parse these responses into lua data structure when combined with the ngx_lua module: https://github.com/agentzh/lua-redis-parser If you only want to use the "get" redis command, you can try out the ngx_redis module here: http://wiki.nginx.org/HttpRedis It returns the parsed content part of the redis response because only "get" is needed to implement. Another option is to parse the redis responses on your client side yourself. Directives redis2_query arg1 arg2 ... Specify a redis command by specifying its individual arguments (including the redis command name itself) in a similar way to the redis-cli utility. Multiple instances of this directive are allowd in a single location and these queries will be pipelined. For example, location /pipelined { redis2_query set hello world; redis2_query get hello; redis2_pass 127.0.0.1:$TEST_NGINX_REDIS_PORT; } then GET /pipelined will yield two successive raw redis responses +OK $5 world while newlines here are actually CR LF ("\r\n"). redis2_raw_query CMD Specify raw redis queries and nginx variables are recognized in the CMD argument. Only one redis command is allowed in the CMD argument, or you'll receive an error. If you want to specify multiple pipelined commands in a single query, use the redis2_raw_queries directive instead. redis2_raw_queries N CMDS Specify N commands in the CMDS argument. Both the N and CMDS arguments can take nginx variables. Here's some examples location /pipelined { redis2_raw_queries 3 "flushall\r\nget key1\r\nget key2\r\n"; redis2_pass 127.0.0.1:6379; } # GET /pipelined2?n=2&cmds=flushall%0D%0Aget%20key%0D%0A location /pipelined2 { set_unescape_uri $n $arg_n; set_unescape_uri $cmds $arg_cmds; redis2_raw_queries $n $cmds; redis2_pass 127.0.0.1:6379; } Note that in the second sample above, the set_unescape_uri directive is provided by the ngx_set_misc module. redis2_literal_raw_query CMD Specify raw redis queries but nginx variables are *not* recognized, that is to say, you're free to use the dollar sign characters ($) in your CMD argument. Only one redis command is allowed in the CMD argument. redis2_pass redis2_connect_timeout syntax: *redis2_connect_timeout <time>* default: *60s* context: *http, server, location* The timeout for connecting to the redis server, in seconds by default. It's wise to always explicitly specify the time unit to avoid confusion. Time units supported are "s"(seconds), "ms"(milliseconds), "y"(years), "M"(months), "w"(weeks), "d"(days), "h"(hours), and "m"(minutes). This time must be less than 597 hours. redis2_send_timeout syntax: *redis2_send_timeout <time>* default: *60s* context: *http, server, location* The timeout for sending TCP requests to the redis server, in seconds by default. It's wise to always explicitly specify the time unit to avoid confusion. Time units supported are "s"(seconds), "ms"(milliseconds), "y"(years), "M"(months), "w"(weeks), "d"(days), "h"(hours), and "m"(minutes). This time must be less than 597 hours. redis2_read_timeout syntax: *redis2_read_timeout <time>* default: *60s* context: *http, server, location* The timeout for reading TCP responses from the redis server, in seconds by default. It's wise to always explicitly specify the time unit to avoid confusion. Time units supported are "s"(seconds), "ms"(milliseconds), "y"(years), "M"(months), "w"(weeks), "d"(days), "h"(hours), and "m"(minutes). This time must be less than 597 hours. redis2_buffer_size redis2_next_upstream syntax: redis2_next_upstream [ error | timeout | invalid_response | off ] default: error timeout context: http, server, location Specify which failure conditions should cause the request to be forwarded to another upstream server. Applies only when the value in redis2_pass is an upstream with two or more servers. Here's an artificial example: upstream redis_cluster { server 127.0.0.1:6379; server 127.0.0.1:6380; } server { location /redis { redis2_next_upstream error timeout invalid_response; redis2_query get foo; redis2_pass redis_cluster; } } Connection Pool You can use Maxim Dounin's excellent ngx_http_upstream_keepalive module ( http://mdounin.ru/hg/ngx_http_upstream_keepalive/ ) with this module to privide TCP connection pool for Redis. A sample config snippet looks like this http { upstream backend { server 127.0.0.1:6379; # a pool with at most 1024 connections # and do not distinguish the servers: keepalive 1024 single; } server { ... location /redis { set_unescape_uri $query $arg_query; redis2_query $query; redis2_pass backend; } } } Lua Interoperability This module can be served as a non-blocking redis2 client for ngx_lua ( http://github.com/chaoslawful/lua-nginx-module ). Here's an example using a GET subrequest: location /redis { internal; # set_unescape_uri is provided by ngx_set_misc set_unescape_uri $query $arg_query; redis2_raw_query $query; redis2_pass 127.0.0.1:6379; } location /main { content_by_lua ' local res = ngx.location.capture("/redis", { args = { query = "ping\\r\\n" } } ) ngx.print("[" .. res.body .. "]") '; } Then accessing /main yields [+PONG\r\n] where "\r\n" is CRLF. That is, this module returns the *raw* TCP responses from the remote redis server. For lua-based application developers, they may want to utilize the lua-redis-parser module (written in pure C) to parse such raw responses into Lua data structures: https://github.com/agentzh/lua-redis-parser When moving the inlined Lua code into an external .lua file, it's important to use the escape sequence "\r\n" directly. We used "\\r\\n" above just because the Lua code itself needs quoting when being put into an nginx string literal. You can also use POST/PUT subrequests to transfer the raw redis request via request body, which does not require URI escaping and unescaping, thus saving some CPU cycles. Here's such an example: location /redis { internal; # $echo_request_body is provided by the ngx_echo module redis2_raw_query $echo_request_body; redis2_pass 127.0.0.1:6379; } location /main { content_by_lua ' local res = ngx.location.capture("/redis", { method = ngx.HTTP_PUT, body = "ping\\r\\n" } ) ngx.print("[" .. res.body .. "]") '; } This yeilds exactly the same output as the previous (GET) sample. One can also use Lua to pick up a concrete Redis backend based on some complicated hashing rules. For instance, upstream redis-a { server foo.bar.com:6379; } upstream redis-b { server bar.baz.com:6379; } upstream redis-c { server blah.blah.org:6379; } server { ... location /redis { set_unescape_uri $query $arg_query; redis2_query $query; redis2_pass $arg_backend; } location /foo { content_by_lua " -- pick up a server randomly local servers = {'redis-a', 'redis-b', 'redis-c'} local i = ngx.time() % #servers + 1; local srv = servers[i] local res = ngx.location.capture('/redis', { args = { query = '...', backend = srv } } ) ngx.say(res.body) "; } } Redis Publish/Subscribe Support This module has limited support for redis publish/subscribe feature. It cannot be fully supported due to the stateless nature of REST and HTTP model. Consider the following example: location /redis { redis2_raw_queries 2 "subscribe /foo/bar\r\n"; redis2_pass 127.0.0.1:6379; } And then publish a message for the key /foo/bar in the redis-cli command line. And then you'll receive two multi-bulk replies from the /redis location. You can surely parse the replies with the lua-redis-parser library if you're using Lua to access this module's location. Some limitations: 1. You cannot use ngx_http_upstream_keepalive with this redis upstream. Only short redis connections will work. 2. There may be some race conditions that produce the harmless "Redis server returned extra bytes" warnings in your nginx's error.log. Such warnings might be rare but just be prepared for it. 3. You should tune the various timeout settings provided by ngx_redis2. Performance Tuning When you're using ngx_redis2, please ensure you're using a tcp connection pool (provided by ngx_http_upstream_keepalive) and redis pipelining wherever possible. These features will significantly improve performance. Also, using multiple instance of redis servers on your multi-core machines also help a lot due to the sequential processing nature of a single redis server instance. Also, when you're benchmarking performance using something like ab or http_load, please ensure that your error log level is high enough (like "warn") to prevent nginx workers spend too much cycles on flushing the error.log file, which is always unbuffered and blocking and thus very expensive. Installation 1. Grab the nginx source code from nginx.net (<http://nginx.net/>), for example, the version 0.8.54 (see nginx compatibility), 2. and then build the source with this module: $ wget 'http://sysoev.ru/nginx/nginx-0.8.54.tar.gz' $ tar -xzvf nginx-0.8.54.tar.gz $ cd nginx-0.8.54/ # Here we assume you would install you nginx under /opt/nginx/. $ ./configure --prefix=/opt/nginx \ --add-module=/path/to/redis2-nginx-module $ make -j2 $ make install Download the latest version of the release tarball of this module from redis2-nginx-module file list (<http://github.com/agentzh/redis2-nginx-module/downloads>). Compatibility Redis 2.0, 2.2, and above should work with this module without any issues. So is the "Alchemy Database" (aka redisql). The following versions of Nginx should work with this module: * 1.0.x (last tested: 1.0.5) * 0.9.x (last tested: 0.9.4) * 0.8.x >= 0.8.31 (last tested: 0.8.54) Earlier versions of Nginx will *not* work. If you find that any particular version of Nginx above 0.8.31 does not work with this module, please consider reporting a bug. Report Bugs Although a lot of effort has been put into testing and code tuning, there must be some serious bugs lurking somewhere in this module. So whenever you are bitten by any quirks, please don't hesitate to 1. send a bug report or even patches to <agentzh@gmail.com>, 2. or create a ticket on the issue tracking interface (<http://github.com/agentzh/redis2-nginx-module/issues>) provided by GitHub. Source Repository Available on github at agentzh/redis2-nginx-module (<http://github.com/agentzh/redis2-nginx-module>). TODO * Add the "redis2_as_json" directive to allow emitting JSON directly. AUTHORS Yichun "agentzh" Zhang (章亦春) < agentzh@gmail.com > Getting involved You'll be very welcomed to submit patches to the author or just ask for a commit bit to the source repository on GitHub. Copyright & License Copyright (c) 2010, 2011 Taobao Inc., Alibaba Group ( http://www.taobao.com ). Copyright (c) 2010, 2011 Yichun "agentzh" Zhang (章亦春) <agentzh@gmail.com>. This module is licensed under the terms of the BSD license. 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. SEE ALSO * a redis response parser for Lua: https://github.com/agentzh/lua-redis-parser