lua getting started demo (read by HelloWorld+redis)

Keywords: Java Redis Docker Nginx

1. lua introduction demo

1.1. Hello World!!

  1. Because I am used to using docker to install various software, this lua script also runs on the docker container
  2. Openresty is a variety of modules of nginx+lua, so you can install openresty directly in docker
  3. Modify the nginx.conf configuration file, and add
lua_package_path "/usr/local/openresty/lualib/?.lua;;";
  1. On the server module in http, add
location /lua-file{
                default_type 'text/html';
                content_by_lua_file /usr/local/openresty/demo/lua-file.lua;
        }
  1. In this way, I can start to write lua script in the specified directory. After writing the script, nginx -s reload can access lua script through IP / lua file in a moment

  2. I write ngx.say('Hello world!! ') in lua-file.lua, and then reload it
  3. Results:

1.2. Visit 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. Of course, I stored the value of key as dog in redis in advance
  2. Access browser results

1.3. summary

  1. Through a simple hello world instance and redis reading, we have a basic understanding of the usage and functions of lua. The syntax of lua is similar to that of js, and some of its own features. Here, I'll give you some suggestions

Posted by HHawk on Sat, 07 Dec 2019 14:38:08 -0800