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類似,部分自己的特色,這里我就拋磚引玉一下了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM