August 2017
Intermediate to advanced
278 pages
8h 53m
English
To implement our simple hit counter, we're going to add a basic location block directive to our main nginx.conf configuration file. Here's the block directive to add:
location /redistest {
default_type 'text/plain';
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("Failed to connect to the redis server, the error was: ", err)
end
local counter = red:get("counter")
if tonumber(counter) == nil then
counter = 0
end
counter = counter + 1
local ok, err = red:set("counter", counter)
ngx.say(counter)
}
}
If we call the /redistest URL, we should see the counter increase each time the page is refreshed.
Read now
Unlock full access