OpenResty入门
写一个小例子--输出随机字符串
编写nginx配置文件
location /random { content_by_lua_file /usr/local/openresty/nginx/conf/lua/random.lua; }
编写random.lua文件
local args = ngx.req.get_uri_args() local salt = args.salt if not salt then ngx.exit(ngx.HTTP_BAD_REQUEST) end local string = ngx.md5(ngx.time() .. salt) ngx.say(string)
检查语法
./nginx -t -c /usr/local/openresty/nginx/conf/nginx.conf
重启nginx
./nginx -s reload -c /usr/local/openresty/nginx/conf/nginx.conf
测试一下
curl 127.0.0.1/random?salt=123
成功输出了随机字符串
ea14f7a36e29925f3e9e318128f989f7
ngx lua API--post请求获取并输出userAgent
1. 编写userAgent.lua文件
local json = require "cjson" ngx.req.read_body() local args = ngx.req.get_post_args() if not args or not args.info then ngx.exit(ngx_HTTP_BAD_REQUEST) end local client_ip = ngx.var.remote_addr local user_agent = ngx.req.get_headers()['user-agent'] or '' local info = ngx.decode_base64(args.info) local response = {} response.info = info response.ip = client_ip response.user_agent = user_agent ngx.say(json.encode(response))
2. 修改nginx配置文件
location /agent { content_by_lua_file /usr/local/openresty/nginx/conf/lua/userAgent.lua; }
3. 检查配置语法并重启nginx
[root@VM_0_10_centos sbin]# ./nginx -t -c /usr/local/openresty/nginx/conf/nginx.conf nginx: the configuration file /usr/local/openresty/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/openresty/nginx/conf/nginx.conf test is successful [root@VM_0_10_centos sbin]# ./nginx -s reload -c /usr/local/openresty/nginx/conf/nginx.conf
4. 使用curl进行测试
[root@VM_0_10_centos sbin]# curl -i --data 'info=addgfdgjkljdfgjkl65632dsgds' 127.0.0.1/agent HTTP/1.1 200 OK Server: openresty/1.13.6.1 Date: Sun, 02 Sep 2018 14:43:31 GMT Content-Type: application/octet-stream Transfer-Encoding: chunked Connection: keep-alive {"info":"i#\b䗮zip":"127.0.0.1","user_agent":"curl\/7.61.0"}
连接数据库--操作MySQL
操作Redis