Skip to content

Instantly share code, notes, and snippets.

@tolitius
Last active June 24, 2023 10:03
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tolitius/23c1db2a69f3de8ec447d7b1e879e648 to your computer and use it in GitHub Desktop.
Save tolitius/23c1db2a69f3de8ec447d7b1e879e648 to your computer and use it in GitHub Desktop.
openresty (nginx + lua): redis connection pooling
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()
}
}
}
}
$ 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