lua入门demo(HelloWorld+redis读取)

1. lua入门demo

1.1. 入门之Hello World!!

  1. 由于我习惯用docker安装各种软件,这次的lua脚本也是运行在docker容器上
  2. openresty是nginx+lua的各种模块,所以直接docker安装openresty
  3. 修改nginx.conf配置文件,在http模块中加上
lua_package_path "/usr/local/openresty/lualib/?.lua;;";
  1. http内的server模块上,在加个
location /lua-file{
                default_type 'text/html';
                content_by_lua_file /usr/local/openresty/demo/lua-file.lua;
        }
  1. 这样我可以在指定目录开始编写lua脚本了,在写完脚本后,nginx -s reload 一下就可以通过ip/lua-file访问lua脚本了

  2. 我在lua-file.lua内先写上 ngx.say('Hello world!!'),然后reload一下后
  3. 访问结果:

751560-20190307110054088-21896768.png

1.2. 访问redis

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 ok,err = red:connect("47.96.64.100",6379)
if not ok then
        ngx.say("connect to redis error: ",err)
        return close_redis(red)
end

local count,err = red:get_reused_times()
if 0 == count then
        ok,err = red:auth("123456")
        if not ok then
                ngx.say("auth fail")
                return
        end
elseif err then
        ngx.say("failed to get reused times: ",err)
        return
end

ngx.say(red:get("dog"))
close_redis(red)
  1. 当然,我事先redis存放了key为dog的值
  2. 访问浏览器结果

751560-20190307113352168-447685689.png

1.3. 总结

  1. 通过简单的hello world实例和redis读取,我们基本了解了lua的用法和功能,lua的语法和js类似,部分自己的特色,这里我就抛砖引玉一下了

转载于:https://www.cnblogs.com/sky-chen/p/10488602.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值