架构图

    

一、准备

1、服务器首先是需要安装redis服务,查看本博客中的另一篇文章
2、安装nginx+luq服务,查看本博客中的另一篇文章

二、下载lua redis库

lua-redis库地址 https://github.com/openresty/lua-resty-redis
cd /data/www/lua/vendor
git clone https://github.com/openresty/lua-resty-redis.git

三、vim nginx.conf,http中添加

lua_package_path "/data/www/lua/vendor/lua-resty-redis/lib/?.lua;;";

四、nginx server中操作redis

1、在nginx.conf中嵌入lua代码

location /hello {
	default_type 'text/json';
	local redis = require "resty.redis";
	local instance = redis:new();
	local host = "127.0.0.1";
	local port = 6379;
	local ok,err = instance:connect(host,port);
	if not ok then
	   ngx.log(ngx.ERR,err);
	   ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE);
	end
	local suc, err instance:set('devil', 'hello world')
	f not suc then
		ngx.say("error")
	else
		ngx.say(instance:get('instance'))
	end
}

2、在实际业务中,独立lua代码(下面是一个redis简单的demo)

2.1、lua文件的代码 vim /data/www/lua/www/redis.lua

#!/usr/local/bin/lua

--[[
	redis操作demo
	Devil
	http://gongfuxiang.com
--]]

-- 引入redis库
local redis = require "resty.redis";

-- 实例化redis
local instance = redis:new();

-- redis配置参数
local host = "127.0.0.1";
local port = 6379;

-- 创建redis连接
local ok,err = instance:connect(host,port);
if not ok then
   ngx.log(ngx.ERR,err);
   ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE);
end

-- 获取客户端post过来的body数据
local request_body = ngx.req.get_body_data() or nil
if( request_body ~= nil )
then
	-- 客户端ip
    local client_ip =ngx.req.get_headers()["X-Real-IP"]
    if client_ip == nil then
            client_ip = ngx.req.get_headers()["x_forworded_for"]
    end
    if client_ip == nil then
            client_ip = ngx.var.remote_addr
    end

    -- 当前时间戳
    local time = os.time()

    -- 拼接redis数据
    local data = client_ip.."{-}"..time.."{-}"..request_body

    -- 队列方式存储redis数据
    local suc, err = instance:lpush('key_list', data)
    if not suc then
        ngx.say('{"code":-2, "msg":"操作失败"}')
    end
    ngx.say('{"code":0, "msg":"操作成功"}')
else
    ngx.say('{"code":-1, "msg":"数据有误"}')
end

五、测试,访问 http://localhost/hello

hello world