OpenResty lua 请求redis服务,openrestyredis


1.环境准备:

1.1 方便学习使用window版本

下载地址:https://github.com/LomoX-Offical/nginx-openresty-windows
下载后,解压到D:\tools\openresty-1.13.6.1-win32
目录是:

image.png

1.2 其中:lua文件夹和lualib是和lua相关的文件。

可以新建文件夹把lua和lualib放到example中目录就变为了


image.png

2. 对\openresty-1.13.6.1-win32\conf\nginx.conf 文件的讲解:

    #user  nobody;
    worker_processes  1;#工作进程数
    events {
            worker_connections  1024;#可连接的数
      }
   http {
          include       mime.types;
          default_type  application/octet-stream;
          sendfile        on;
          keepalive_timeout  65;
          server {
                listen       80; #监听端口
                server_name  localhost;
                location / {
                      root   html;
                      index  index.html index.htm;
                }
                error_page   500 502 503 504  /50x.html;
                location = /50x.html {
                    root   html;
                }
         }

2.1 对因为lua相关的文件库都放到example目录中,所以需要配置

http {
    #window环境的路径需要注意\\转义的问题
lua_package_path "D:\\tools\openresty-1.13.6.1-win32\example\lualib/?.lua;;";   
lua_package_cpath "D:\\tools\openresty-1.13.6.1-win32\example\lualib/?.so;;";
    include       mime.types;
    include       D:\\tools\openresty-1.13.6.1-win32\example\example.conf;
    default_type  application/octet-stream;
    .........
      }

2.2 在example目录中新建example.conf文件

  example目录结构为:
image.png

example.conf内容为:
server {
listen 80;
server_name _;

location /lua {
    default_type 'text/html';  
    lua_code_cache on;  
    content_by_lua_file D:\\tools\openresty-1.13.6.1-win32\example\lua/test.lua;  
}

location /lua_redis_basic {  
    default_type 'text/html';  
    lua_code_cache off;  
    content_by_lua_file D:\\tools\openresty-1.13.6.1-win32\example\lua/test_redis_basic.lua;  
}

}
一个是访问:/lua 测试是否配置正确,一个是访问 /lua_redis_basic 去请求redis服务

2.3 在\example\lua\目录下新建test.lua 文件

     文件内容为: ngx.say("hello world");

然后 屏蔽example.conf 中的 location /lua_redis_basic方法,启动nginx,查看是否配置正确。
启动命令:start nginx.exe
查看是否启动成功:

image.png
出现上图信息,说明启动成功.
访问127.0.0.1/lua
image.png
页面出现hello world 说明配置成功。

3. 开始配置lua访问redis服务

3.1 在\openresty-1.13.6.1-win32\example\lualib 目录下新建util文件夹

创建:redisUtil.lua文件: 这个文件内容主要是连接redis的公共方法。

local redis = require "resty/redis"

local log = ngx.log
local ERR = ngx.ERR
local setmetatable = setmetatable

local _M = {
}

local mt = { __index = _M }

local function errlog(...)
    log(ERR, "Redis: ", ...)
end

function _M.exec(self, func)

    local red = redis:new()
    red:set_timeout(self.timeout)

    local ok, err = red:connect(self.host, self.port)
    if not ok then
        errlog("Cannot connect, host: " .. self.host .. ", port: " .. self.port)
        return nil, err
    end

    if self.password ~= '' then
         -- 请注意这里 auth 的调用过程
            local count
            count, err = red:get_reused_times()
            if 0 == count then
                ok, err = red:auth(self.password)
                if not ok then
                    ngx.say("failed to auth: ", err)
                    return
                end
           elseif err then
                ngx.say("failed to get reused times: ", err)
                return
          end
    end

    red:select(self.database)

    local res, err = func(red)
    if res then
        local ok, err = red:set_keepalive(self.max_idle_time, self.pool_size)
        if not ok then
            red:close()
        end
    end
    return res, err
end

function _M.new(opts)
    local config = opts or {}
    local self = {
        host = config.host or "127.0.0.1",
    password = config.password or '',
        port = config.port or 6379,
        timeout = config.timeout or 5000,
        database = config.database or 0,
        max_idle_time = config.max_idle_time or 60000,
        pool_size = config.pool_size or 100
    }
    return setmetatable(self, mt)
end

return _M

3.2 \openresty-1.13.6.1-win32\example\lua文件夹下新建test_redis_basic.lua文件

文件内容:

local request_method = ngx.var.request_method
local args = nil

--1、获取参数的值 获取前端提交参数
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
local operation = args["operation"]
if operation == nil then
   operation ="set"
end
local redisUtil = require "util/redisUtil"
local red = redisUtil.new({host = "redis服务地址",password="redis.conf中设置的密码"})
local res, err = red:exec(
    function(red)
        if operation =="get" then
        return red:get("test.lua.redis")
    else
        red:init_pipeline()
        red:set("test.lua.redis", "set hello world wenjun")
        red:expire("test.lua.redis", 600)
        return red:commit_pipeline()
    end
    end
)
if not res then  
     ngx.say(operation.."操作没有返回值");
else
    ngx.say(res);
end 

主要是说明是operation参数判断值是get或是其他参数,get就获取redis的key值返回,其它就是触发保存key值为“test.lua.redis”的数据到value中。

3.3 测试是否配置成功

3.3.1 GET方式测试:

通过在url中输入http://127.0.0.1/lua_redis_basic
页面返回:

image.png
说明保存redis服务成功!
在输入:http://127.0.0.1/lua_redis_basic?operation=get
image.png
说明GET方式成功。

3.3.2 POST方式测试:

通过postman工具进行测试:


image.png

说明POST方式获取成功。

4.redis服务配置需要注意点:

1)主要是redis.conf 文件进行修改:
bind 127.0.0.1 注释掉
2)Redis默认不是以守护进程的方式运行,可以通过该配置项修改,使用yes启用守护进程,设置为no
daemonize no
3)保护模式
protected-mode no
4)添加认证,设置密码
找到#requirepass foobared下面添加:
requirepass ‘密码值’

相关内容

    暂无相关文章