zoukankan      html  css  js  c++  java
  • 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. 访问结果:

    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. 访问浏览器结果

    1.3. 总结

    1. 通过简单的hello world实例和redis读取,我们基本了解了lua的用法和功能,lua的语法和js类似,部分自己的特色,这里我就抛砖引玉一下了
  • 相关阅读:
    Atom使用教程
    4-[函数]-参数
    4-[函数]- 独立功能的代码块
    3 [文件]-修改文件
    2 [文件]-文件操作
    1. [文件]- 文件类型,文件open模式
    2-16 阶段考核
    react native 网络get请求方式参数不可为undefined或null
    [网络]远程访问局域网svn服务器[转]
    react native listview 一个有用的属性,用作两列布局
  • 原文地址:https://www.cnblogs.com/sky-chen/p/10488602.html
Copyright © 2011-2022 走看看