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. 访问结果:

lua入门demo(HelloWorld+redis读取)

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

lua入门demo(HelloWorld+redis读取)

1.3. 总结

  1. 通过简单的hello world实例和redis读取,我们基本了解了lua的用法和功能,lua的语法和js类似,部分自己的特色,这里我就抛砖引玉一下了
上一篇:关于MyEclipse启动报错:Error starting static Resources;下面伴随Failed to start component [StandardServer[8005]]; A child container failed during start.的错误提示解决办法.


下一篇:ROW_NUMBER() OVER(PARTITION BY COLUMN ORDER BY COLUMN DESC)函数的使用