0x7OpenResty系列:Openresty最佳案例| 第7篇:模块开发,OpenResty连接Redis

举报
云享专家 发表于 2019/09/30 14:23:43 2019/09/30
【摘要】 上面的代码很简单,通过连接池连接的Redis,连接上的Redis后,通过设置一对键值对(味精,HELLOWORD)到Redis的中,然后GET(MSG),并通过ngx.say()返回给浏览器。

Lua的模块开发

在实际的开发过程中,不可能把所有的LUA代码写在一个lua的文件中,通常的做法将特定功能的放在一个lua的文件中,即用LUA模块开发。在lualib目录下,默认有以下的LUA模块。

lualib/
├── cjson.so
├── ngx
│   ├── balancer.lua
│   ├── ocsp.lua
│   ├── re.lua
│   ├── semaphore.lua
│   ├── ssl
│   │   └── session.lua
│   └── ssl.lua
├── rds
│   └── parser.so
├── redis
│   └── parser.so
└── resty
    ├── aes.lua
    ├── core
    │   ├── base64.lua
    │   ├── base.lua
    │   ├── ctx.lua
    │   ├── exit.lua
    │   ├── hash.lua
    │   ├── misc.lua
    │   ├── regex.lua
    │   ├── request.lua
    │   ├── response.lua
    │   ├── shdict.lua
    │   ├── time.lua
    │   ├── uri.lua
    │   ├── var.lua
    │   └── worker.lua
    ├── core.lua
    ├── dns
    │   └── resolver.lua
    ├── limit
    │   ├── conn.lua
    │   ├── req.lua
    │   └── traffic.lua
    ├── lock.lua
    ├── lrucache
    │   └── pureffi.lua
    ├── lrucache.lua
    ├── md5.lua
    ├── memcached.lua
    ├── mysql.lua
    ├── random.lua
    ├── redis.lua
    ├── sha1.lua
    ├── sha224.lua
    ├── sha256.lua
    ├── sha384.lua
    ├── sha512.lua
    ├── sha.lua
    ├── string.lua
    ├── upload.lua
    ├── upstream
    │   └── healthcheck.lua
    └── websocket
        ├── client.lua
        ├── protocol.lua
        └── server.lua


在使用这些模块之前,需要在nginx的的配置文件nginx.conf中的HTTP模块加上以下的配置:

 lua_package_path "/usr/example/lualib/?.lua;;";  #lua 模块
 lua_package_cpath "/usr/example/lualib/?.so;;";  #c模块


现在来简单的开发一个LUA模块:

vim /usr/example/lualib/module1.lua


module1.lua文件加上以下的代码:

local count = 0
local function hello()
   count = count + 1
   ngx.say("count : ", count)
end
 
local _M = {
   hello = hello
}
 
return _M


开发时将所有数据局部变量/局部函数;通过_M导入要暴露的函数,实现嵌入封装。

在/ usr / example / lua目录下创建一个test_module_1.lua文件,在该文件中引用上面的module1.lua文件。

vim /usr/example/lua/test_module_1.lua


加上以下代码:

local module1 = require("module1")
 
module1.hello()


通过要求(模块名)来加载模块,如果是多级目录,则需要通过要求(目录1.目录2.模块名)加载。

/user/example/example.conf中加上以下的配置:

location /lua_module_1 {
    default_type 'text/html';
    lua_code_cache on;
    content_by_lua_file /usr/example/lua/test_module_1.lua;
}


多次在浏览器***问:HTTP//116.196.177.123/lua_module_1,浏览器显示:

count : 1
count : 2
count : 3
 
...

 

安装的Redis

linux下安装:
cd / usr / servers

$ wget http://download.redis.io/releases/redis-3.2.6.tar.gz
$ tar xzf redis-3.2.6.tar.gz
$ cd redis-3.2.6
$ make


启动Redis的:

nohup /usr/servers/redis-3.2.6/src/redis-server  /usr/servers/redis-3.2.6/redis.conf &


查看是否启动:

ps -ef |grep redis


终端显示:

root     20985 14268  0 18:49 pts/0    00:00:00 /usr/servers/redis-3.2.6/src/redis-server 127.0.0.1:6379


可见的Redis已经启动。

LUA连接的Redis

lua_resty_redis模块地址:HTTPS//github.com/openresty/lua-resty-redis

lua-resty-redis-基于cosocket APIngx_luaLua Redis客户端驱动程序

lua_resty_redis它是一个基于cosocket API的为ngx_lua模块提供Lua redis客户端的驱动。

创建一个test_redis_basic.lua文件

vim /usr/example/lua/test_redis_basic.lua

 local function close_redis(red)
    if not red then
        return
    end
 
    local pool_max_idle_time = 10000 --毫秒
    local pool_size = 100 --连接池大小
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
    if not ok then
        ngx.say("set keepalive error : ", err)
    end
end
 
local redis = require("resty.redis")
 
 
local red = redis:new()
 
red:set_timeout(1000)
 
local ip = "127.0.0.1"
local port = 6379
local ok, err = red:connect(ip, port)
if not ok then
    ngx.say("connect to redis error : ", err)
    return close_redis(red)
end
 
ok, err = red:set("msg", "hello world")
if not ok then
    ngx.say("set msg error : ", err)
    return close_redis(red)
end
 
 
local resp, err = red:get("msg")
if not resp then
    ngx.say("get msg error : ", err)
    return close_redis(red)
end
 
if resp == ngx.null then
    resp = ''
end
ngx.say("msg : ", resp)
 
close_redis(red)


上面的代码很简单,通过连接池连接的Redis,连接上的Redis后,通过设置一对键值对(味精,HELLOWORD)到Redis的中,然后GETMSG),并通过ngx.say()返回给浏览器。

vim /usr/example/example.conf,添加以下的配置代码:

location /lua_redis_basic {
    default_type 'text/html';
    lua_code_cache on;
    content_by_lua_file /usr/example/lua/test_redis_basic.lua;
 }


浏览器访问:HTTP//116.196.177.123/lua_redis_basic

浏览器显示:

msg:世界你好

lua_resty_redis支持所有的Redis的指令,本身的Redis就支持LUA语言操作。所以lua_resty_redis模块能够提高所有的Redis的操作的功能。

在很多时候,Redis是设置了密码的,连接时,如果需要验证密码,需要添加本地资源,err = redauth“ foobared”),示例代码如下:

  local redis = require "resty.redis"
    local red = redis:new()
 
    red:set_timeout(1000) -- 1 sec
 
    local ok, err = red:connect("127.0.0.1", 6379)
    if not ok then
        ngx.say("failed to connect: ", err)
        return
    end
 
    local res, err = red:auth("foobared")
    if not res then
        ngx.say("failed to authenticate: ", err)
        return
    end


请更多关注的官方文档https://github.com/openresty/lua-resty-redis
状语从句:开涛的博客http://jinnianshilongnian.iteye.com/blog/2187328

 

原创作者:方志朋

方志朋简介:SpringCloud中国社区联合创始人,博客访问量突破一千万,爱好开源,热爱分享,活跃于各大社区,保持着非常强的学习驱动力,终身学习践行者,终身学习受益者。目前就职于国内某家知名互联网保险公司,担任DEVOPS工程师,对微服务领域和持续集成领域研究较深,精通微服务框架SpringCloud


【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。