前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >lua入门demo(HelloWorld+redis读取)

lua入门demo(HelloWorld+redis读取)

作者头像
老梁
发布2019-09-10 18:25:51
7090
发布2019-09-10 18:25:51
举报

1. lua入门demo

1.1. 入门之Hello World!!

  1. 由于我习惯用docker安装各种软件,这次的lua脚本也是运行在docker容器上
  2. openresty是nginx+lua的各种模块,所以直接docker安装openresty
  3. 修改nginx.conf配置文件,在http模块中加上
代码语言:javascript
复制
lua_package_path "/usr/local/openresty/lualib/?.lua;;";
  1. http内的server模块上,在加个
代码语言:javascript
复制
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. 访问结果:

1.2. 访问redis

代码语言:javascript
复制
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. 访问浏览器结果

1.3. 总结

  1. 通过简单的hello world实例和redis读取,我们基本了解了lua的用法和功能,lua的语法和js类似,部分自己的特色,这里我就抛砖引玉一下了
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-03-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. lua入门demo
    • 1.1. 入门之Hello World!!
      • 1.2. 访问redis
        • 1.3. 总结
        相关产品与服务
        云数据库 Redis
        腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档