33、Nginx + OpenResty + Redis 采用Lua脚本方式自取Redis缓存信息

安装攻略,请参照 https://blog.csdn.net/crystalcs2010/article/details/89027002

这里只针对Nginx 配置文件以及Lua脚本做描述

nginx.conf 添加如下代码

location /lua_get {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Requested-With';
    add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
    default_type 'text/plain';
    charset 'utf-8';
    content_by_lua_file /usr/local/openresty/nginx/lua/get.lua;
}

切换目录

# cd /usr/local/openresty/nginx/lua

# vi get.lua

get.lua 添加如下代码

-- 获取以GET方式传参的数据
local args = ngx.req.get_uri_args()

local key = args["key"]

--连接Redis
local cjson = require "cjson"
local redis = require "resty.redis"
local red = redis:new()
local ok, err = red:connect('192.168.52.132','6379')
red:set_timeout(60000)
if not ok then
        ngx.say("failed to connect: ", err)
        return
end
--ngx.say("connection result",ok)
--密码校验
local count, err = red:get_reused_times()
--ngx.say(count)
if 0 == count then
        local ok, err = red:auth("Heroic1234!")
        if not ok then
                ngx.say("failed to auth", err)
                return
        else
                --ngx.say("auth success ", ok)
        end
elseif err then
        ngx.say("failed to get reused times:", err)
        return
end
--获取key的缓存信息
local resp, err = red:get(key)
ngx.say(resp)

保存并退出

重启Nginx服务

运行结果

33、Nginx + OpenResty + Redis 采用Lua脚本方式自取Redis缓存信息_第1张图片

33、Nginx + OpenResty + Redis 采用Lua脚本方式自取Redis缓存信息_第2张图片

 

 

你可能感兴趣的:(Linux)