nginx安装lua直连redis

2021/4/26 19:29:48

本文主要是介绍nginx安装lua直连redis,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

nginx安装lua直连redis

    • linux安装LuaJIT
    • ngx_devel_kit和lua-nginx-module
    • 实现lua连接redis

linux安装LuaJIT

##安装必要的依赖
yum install readline-devel
wget http://luajit.org/download/LuaJIT-2.0.4.tar.gz
tar -zxvf LuaJIT-2.0.4.tar.gz
cd LuaJIT-2.0.2
make install PREFIX=/usr/local/LuaJIT

##然后配置环境变量
vim /etc/profile
exportLUAJIT_LIB=/usr/local/LuaJIT/lib
exportLUAJIT_INC=/usr/local/LuaJIT/include/luajit-2.0

##使环境变量生效
source /etc/profile

##lua 语言输出hello world
vim HelloWorld.lua
print(“Hello World!”)

代码验证,命令行输入
lua HelloWorld.lua

ngx_devel_kit和lua-nginx-module

lua-nginx-module是nginx的lua模块

  1. mkdir-p /usr/local/src/nginx
  2. cd /usr/local/src/nginx
  3. wget https://github.com/simpl/ngx_devel_kit/archive/v0.3.0.tar.gz
  4. wget https://github.com/openresty/lua-nginx-module/archive/v0.10.9rc7.tar.gz
  5. tar xf v0.3.0.tar.gz
  6. tar xf archive/v0.10.9rc7.tar.gz
  7. nginx重新编译
  8. nginx -v 查看以前的参数,在最后加上新增的模块,如下
  9. ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-stream --add-module=/usr/local/nginx/ngx_devel_kit-0.3.0 --add-module=/usr/local/nginx/lua-nginx-module-0.10.9rc7
  10. make && make install
    11.ldconfig
    12.nginx -V 查看模块是否添加成功,可能有如下报错

nginx: error while loading shared libraries: libluajit-5.1.so.2: cannot open shared objectfile: No such file or directory

解决办法:
find / -name libluajit-5.1.so.2
vim /etc/ld.so.conf.d/libc.conf
添加 /usr/local/LuaJIT/lib
保存重新查看
ldconfig
nginx -v

实现lua连接redis

  1. 下载lua-redis-cluster(连接redis-cluster集群) 客户端
    cd /usr/share/lua/5.1
    git clone https://github.com/onlonely/lua-redis-cluster.git
  2. 下载快速JSON编码/解析
    cd /usr/share/lua/5.1
    git clone https://github.com/openresty/lua-cjson.git
  3. 下载 lua-resty-redis (单机版redis)客户端
    cd /usr/share/lua/5.1
    git clone https://github.com/openresty/lua-resty-redis
  4. lua连接单机版本redis,编辑nginx.conf脚本

user  root;
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    #lua_package_path "/usr/share/lua/5.1/lua-resty-redis/lib/?.lua;;";

    lua_package_path "/usr/share/lua/5.1/lua-resty-redis/lib/?.lua;;/usr/share/lua/5.1/lua-resty-redis-cluster/lib/resty‘7/?.lua;;";

lua_package_cpath "/usr/share/lua/5.1/lua-resty-redis-cluster/lib/libredis_slot.so;;";

sendfile        on;
keepalive_timeout  65;
server {
        listen       80;
        access_log  /usr/local/nginx/logs/$host  main;
        location / {
            root   /www;
            default_type text/html;
        }

       location /lua {
        set $test "hello,world";
        content_by_lua '
            ngx.header.content_type="text/plain"
            ngx.say(ngx.var.test)
        ';

        }
        location /lua_redis {
            content_by_lua_file /etc/nginx/lua/lua_redis.lua;
        }
        #这次的操作,主要是加入了下面这几行代码
        location /lua_redis_sku_num {
            #将要执行的lua操作的redis库存代码封装在/etc/nginx/lua/lua_redis.lua中
            content_by_lua_file /etc/nginx/lua/lua_redis_sku_num.lua;
        }

        location  ~ \.php/?.*  {
                default_type text/html;
                #做php-fpm 配置,注意地址
                root           /www;  #php-fpm容器当中的路径,不是nginx容器路径
                fastcgi_index  index.php;

                fastcgi_pass   172.17.0.2:9000; #php容器端口

                #为php-fpm指定的根目录
                fastcgi_param  SCRIPT_FILENAME  $DOCUMENT_ROOT$fastcgi_script_name;
                #注意是容器当中的位置

                #定义变量 $path_info ,用于存放pathinfo信息
                set $path_info "";
                if ($fastcgi_script_name ~ "^(.+?\.php)(/.+)$") {
                        #将文件地址赋值给变量 $real_script_name
                        set $real_script_name $1;
                            #将文件地址后的参数赋值给变量 $path_info
                        set $path_info $2;
                    }
                     #配置fastcgi的一些参数
                    fastcgi_param SCRIPT_NAME $real_script_name;
                    fastcgi_param PATH_INFO $path_info;
                    include        /usr/local/nginx/conf/fastcgi_params;
             }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
              root   html;
        }
    }

}

  1. lua_redis.lua
local function close_redis(redis_instance)
    if not redis_instance then
        return
    end
    local ok,err = redis_instance:close();
    if not ok then
        ngx.say("close redis error : ",err);
    end
end

local redis = require("resty.redis");
--local redis = require "redis"
-- 创建一个redis对象实例。在失败,返回nil和描述错误的字符串的情况下
local redis_instance = redis:new();
--设置后续操作的超时(以毫秒为单位)保护,包括connect方法
redis_instance:set_timeout(1000)
--建立连接
local ip = '192.168.162.133'
local port = 6380
--尝试连接到redis服务器正在侦听的远程主机和端口
local ok,err = redis_instance:connect(ip,port)
if not ok then
    ngx.say("connect redis error : ",err)
    return close_redis(redis_instance);
end

--Redis身份验证
--local auth,err = redis_instance:auth("");
--if not auth then
--    ngx.say("failed to authenticate : ",err)
--end

--调用API进行处理
local resp,err = redis_instance:set("msg","hello world")
if not resp then
    ngx.say("set msg error : ",err)
    return close_redis(redis_instance)
end

--调用API获取数据
local resp, err = redis_instance:get("msg")
if not resp then
    ngx.say("get msg error : ", err)
    return close_redis(redis_instance)
end

--得到的数据为空处理
if resp == ngx.null then
    resp = 'this is not redis_data'  --比如默认值
end
ngx.say("msg : ", resp)

close_redis(redis_instance)
  1. llua_redis_sku_num.lua
--Nginx服务器中使用lua获取get或post参数
local request_method = ngx.var.request_method
local args = nil
local param = nil
--获取参数的值
if "GET" == request_method then
    args = ngx.req.get_uri_args()
elseif "POST" == request_method then
    ngx.req.read_body()
    args = ngx.req.get_post_args()
end
sku_id = args["sku_id"]



local function close_redis(redis_instance)
    if not redis_instance then
        return
    end
    local ok,err = redis_instance:close();
    if not ok then
        ngx.say("close redis error : ",err);
    end
end


local redis = require("resty.redis");
--local redis = require "redis"
-- 创建一个redis对象实例。在失败,返回nil和描述错误的字符串的情况下
local redis_instance = redis:new();
--设置后续操作的超时(以毫秒为单位)保护,包括connect方法
redis_instance:set_timeout(1000)
--建立连接
local ip = '127.0.0.1'
local port = 6379
--尝试连接到redis服务器正在侦听的远程主机和端口
local ok,err = redis_instance:connect(ip,port)
if not ok then
    ngx.say("connect redis error : ",err)
    return close_redis(redis_instance);
end

--Redis身份验证
--local auth,err = redis_instance:auth("");
--if not auth then
--    ngx.say("failed to authenticate : ",err)
--end


--调用API获取数据
local prifex = "sku_num_"
ngx.say(sku_id)

if (sku_id == nil) then
    ngx.say("sku_id is null")
    return close_redis(redis_instance);
end

local key = prifex .. sku_id
local resp, err = redis_instance:get("sku_num_123")
if not resp then
    ngx.say("get msg error : ", err)
    return close_redis(redis_instance)
end

--得到的数据为空处理
if resp == ngx.null then
    resp = 'this is not redis_data'  --比如默认值
end
ngx.say("msg : ", resp)

close_redis(redis_instance)

测试
命令行运行
curl 127.0.0.1/lua
hello,world

curl 127.0.0.1/lua_redis
msg : hello world
reids新增一个健,健名为redis

curl 127.0.0.1/lua_redis_sku_num?sku_id=123
123
msg : 111
获取健名为sku_num_123的值



这篇关于nginx安装lua直连redis的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程