一、在lua中执行shell脚本并取得shell执行返回结果
lua脚本中可以直接执行shell脚本,常用的方法是os.execute,但是这个方法不能返回执行结果。
os.execute() : This function is equivalent to the C function system. It passes command to be executed by an operating system shell. It returns a status code, which is system-dependent. If command is absent, then it returns nonzero if a shell is available and zero otherwise
io.popen()方法可以实现,io.popen()执行命令后返回的是一个文件,然后使用lua中文件的读取命令,取得内容。示例
local rsfile = io.popen('pwd')
local rschar = rsfile:read("*all")
ngx.say(rschar)
io.popen() : Starts program prog in a separated process and returns a file handle that you can use to read data from this program (if mode is r, the default) or to write data to this program (if mode is w). This function is system dependent and is not available on all platforms.
如上即可实现执行shell脚本并打印出来。lua对os,文件还有其它的操作方法截图如下,对操作系统可使用的方法:
对文件可使用的方法:
二、lua使用nginx连接池连接redis出现bad request
lua连接redis有一个比较好的方法就是使用nginx的连接池。通过对连接池中的连接的重复利用,避免总是要去进行连接redis消耗时间,从而可以搭建高并发Web应用,外部l请求Nginx,Nginx通过Lua访问Redis,返回json数据。注这里使用的是:(openresty/lua-resty-redis),基本的操作方法如下:
local sock = ngx.socket.tcp()
sock:settimeout(连接超时时间设置值)
sock:connect(redis的IP地址,redis端口)
sock:send(组装后的发送数据)
sock:receive()
sock:setkeepalive(连接持续时间配置值, 连接个数配置大小) --此条后关键,每次调用后。
网上已经有雷锋给我们开发好了模块了。https://github.com/openresty/lua-resty-redis#limitations 非常好用。不过对接口进行压力测试时,发现总有非常多的接口调用失败,大量出现bad request 错误。
一直找不到原因,而53这行代码正是使用openresty/lua-resty-redis 执行local ok, err = red:connect("127.0.0.1", 6379) 这句连接redis的时候,所幸在网上看到一点提示,然后在github上也看到了作者也说了,
即在加载redis模块的时候 ,将值存储在local变量中(ngx.ctx table我没试过),否则会出现很多bad request ,而我正是考虑代码复用,将redis的加载和连接池初始化过程放在了页面初始位置处导致的。经过这样更改后,一切都OK了,单台服务器并发压力测试5000都没有出现数据丢失。足够对付我们的需求了。