1024programmer Nginx Use Lua scripting language to operate Redis in Nginx server

Use Lua scripting language to operate Redis in Nginx server

Use the Lua scripting language to operate Redis.

Since a lot of Lua code is written in Nginx
, it will make the configuration file very cumbersome, so here use content_by_lua_file to introduce Lua
script file.

To use content_by_lua_file, the nginx_lua_module module needs to be installed.

Installation introduction, click here: nginx_lua_module

The great god Zhang Yichun provides a very convenient development kit, as follows:

git clone https://github.com/agentzh/lua-resty-redis.git

In this package, there is a Lib directory, copy the files and subdirectories under the Lib directory to the directory /data/www/lua

In the Nginx configuration file, you need to add a line of code to import redis.lua.

Note: Add in the http segment.

lua_package_path “/data/www/lua/?.lua;;”;

In order to make the modification of the lua script take effect in time, a line of code needs to be added, as follows:

Note: In the server section, add code. If you do not add this code or set it to on, you need to restart Nginx.

lua_code_cache off;

In the Nginx configuration file, add a Location:

location /lua {
content_by_lua_file /data/www/lua/test.lua;
}

Note: import test.lua script file

Lua script file: test.lua.

local redis = require “resty.redis”
local cache = redis.new()
local ok, err = cache.connect(cache, ‘127.0.0.1’, ‘6379’)
cache:set_timeout(60000)
if not ok then
ngx.say(“failed to connect:”, err)
return
end
res, err = cache: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 = cache: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)
local ok, err = cache:close()
if not ok then
ngx.say(“failed to close:”, err)
return
end
The test results are as follows:
[root@localhost conf]# curl http://localhost/lua
set result: OK
dog: an aniaml
Success!

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/use-lua-scripting-language-to-operate-redis-in-nginx-server/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索