1、这里我们假定,同时要访问多个数据源
而且,查询是没有依赖关系的,那我们就可以同时发出请求
这样我总的延时,是我所有请求中最慢的一个所用时间,而不是原先的所有请求用时的叠加!
这种方式,就是用并发换取了响应时间
location = /api {
content_by_lua '
local res1, res2, res3 =
ngx.location.capture_multi{
{"/memc"}, {"/mysql"}, {"/postgres"}
}
ngx.say(res1.body, res2.body, res3.body)
';
}
这里我们就同时发出了3个请求
同时到 memcached/mysql/pg
然后全新响应后,将結果放到 res1/2/3 三个变量中返回
2、我们想在多个进程间共存配置/业务数据
lua_shared_dict dogs 10m;
server {
location = /set {
content_by_lua '
local dogs = ngx.shared.dogs
dogs:set("Tom", ngx.var.arg_n)
ngx.say("OK")
'
}
location = /get {
content_by_lua '
local dogs = ngx.shared.dogs
ngx.say("Tom: ", dogs.get("Tom"))
';
}
}
上面这个例子:
首先,使用 lua_shared_dict 分配一 10M 的空间
然后,使用 OOP 方式来定义两个接口:一个 /set 一个/get
然后,不论哪个 worker 具体调用哪个操作
但是结果是終保存一致的
5、md5:
http://xxx/md5?a=test
location = /md5{
set_unescape_uri $a $arg_a;
echo $a;
set_md5 $key;
echo $key;
}
输出 test d41d8cd98f00b204e9800998ecf8427e #输出的md5与php下计算出来的不同
location = /md5lua{
content_by_lua '
local key = ngx.var.arg_a;
local md5 = ngx.md5(key) ;
ngx.say(md5);
';
}
以上两种和php计算不一样。
5、修改url参数:
location = /t {
rewrite_by_lua '
local args = ngx.req.get_uri_args()
args.SID = nil
args.UID = nil
ngx.req.set_uri_args(args)
';
echo $args;
}
$ curl 'localhost:8081/t?RT=62&SID=BC3781C3-2E02-4A11-89CF-34E5CFE8B0EF&UID=44332&L=EN&M=1&H=1&UNC=0&src="http://chattool.sinaapp.com/LK"'
M=1&UNC=0&RT=62&H=1&L=EN&src="http://chattool.sinaapp.com/LK
6、获取及设置cookie
1) 获取所有cookie
ngx.var.http_cookie
如:nickname=user-1465294791; token=22413d5a1187e48af9ddf19b0f800c6e; uid=1465294791
2) 设置cookie
ngx.header['Set-Cookie'] = {"visit_version=123;expires=Wed, 27-Mar-2014 16:39:44 GMT"};
3) 获取cookie: ngx.var.cookie_cookieName
ngx.var.cookie_visit_version
7、lua_shared_dict
syntax:lua_shared_dict <name> <size>
default: no
context: http
phase: depends on usage
声明一个共享内存区域 name,以充当基于 Lua 字典 ngx.shared.<name>
的共享存储。
共享内存总是被当前 Nginx 服务器实例中所有的 Nginx worker 进程所共享。
size 参数接受大小单位,如 k,m:
http {
lua_shared_dict dogs 10m;
...
}