Last active
June 24, 2023 10:03
-
-
Save tolitius/23c1db2a69f3de8ec447d7b1e879e648 to your computer and use it in GitHub Desktop.
openresty (nginx + lua): redis connection pooling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
worker_processes 1; | |
error_log logs/error.log; | |
events { | |
worker_connections 1024; | |
} | |
http { | |
init_worker_by_lua_block { | |
redis = require("resty.redis") | |
} | |
server { | |
listen 8080; | |
lua_code_cache on; | |
location /dbg { | |
content_by_lua_block { | |
require('resty.repl').start() | |
} | |
} | |
location /ping { | |
content_by_lua_block { | |
local red = redis:new() | |
local ok, err = red:connect("127.0.0.1", 6379) | |
if not ok then | |
ngx.say("failed to connect: ", err) | |
return | |
end | |
ngx.say("reused times: ", red:get_reused_times()) | |
red:set_keepalive() | |
local red = redis:new() | |
local ok, err = red:connect("127.0.0.1", 6379) | |
if not ok then | |
ngx.say("failed to connect: ", err) | |
return | |
end | |
ngx.say("reused times: ", red:get_reused_times()) | |
red:set_keepalive() | |
} | |
} | |
location /pong { | |
content_by_lua_block { | |
local red = redis:new() | |
local ok, err = red:connect("127.0.0.1", 6379) | |
if not ok then | |
ngx.say("failed to connect: ", err) | |
return | |
end | |
ngx.say("reused times: ", red:get_reused_times()) | |
red:set_keepalive() | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ curl 127.0.0.1:8080/ping | |
reused times: 0 | |
reused times: 1 | |
$ curl 127.0.0.1:8080/ping | |
reused times: 2 | |
reused times: 3 | |
$ curl 127.0.0.1:8080/pong | |
reused times: 4 | |
$ curl 127.0.0.1:8080/pong | |
reused times: 5 | |
$ curl 127.0.0.1:8080/ping | |
reused times: 6 | |
reused times: 7 | |
$ curl 127.0.0.1:8080/pong | |
reused times: 8 | |
$ curl 127.0.0.1:8080/ping | |
reused times: 9 | |
reused times: 10 | |
$ curl 127.0.0.1:8080/pong | |
reused times: 11 | |
$ curl 127.0.0.1:8080/ping | |
reused times: 12 | |
reused times: 13 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment