yml文件:
version: "3" services: openresty: image: openresty/openresty:latest container_name: openresty cpu_shares: 512 mem_limit: 200m ports: - 80:80 volumes: - ./config/nginx.conf:/usr/local/openresty/nginx/conf/nginx.conf restart: unless-stopped
进入容器:
docker exec -it openresty /bin/bash
nginx.conf内容如下:
worker_processes 4;
events {
worker_connections 1024;
}
http {
server {
listen 80;
location / {
default_type "text/plain";
content_by_lua_block {
ngx.say("Hello, OpenResty!")
}
}
}
}如果要输出JSON的话,可以参考:
content_by_lua_block {
local cjson = require "cjson"
local data = {
name = "florent",
age = 100
}
ngx.say(cjson.encode(data))
}得到Get请求的值:
local args = ngx.req.get_uri_args()
ngx.say("name: ", args["name"]) 读取post请求的JSON数据:
ngx.req.read_body() -- 读取请求体
local data = ngx.req.get_body_data()
if not data then
ngx.say("failed to get JSON data")
return
end
-- 解析 JSON 数据
local json = require("cjson.safe")
local decoded, err = json.decode(data)
if not decoded then
ngx.say("failed to decode JSON data: ", err)
return
end
-- 访问 JSON 数据
ngx.say("name: ", decoded["name"])
ngx.say("age: ", decoded["age"])这个代码将会输出 POST 请求中的 JSON 数据中名为 name 和 age 的字段的值。需要注意的是,在使用 get_body_data() 方法之前,需要先调用 read_body() 方法来读取请求体,否则可能会出现错误。
另外,也可以通过 ngx.req.get_body_file() 方法来获取上传文件的信息和内容。需要注意的是,在使用这些方法获取 HTTP 请求参数和信息时,要遵循最佳实践和指南,并注意安全性和可靠性,以确保服务器和应用程序的安全和稳定性。
获取请求头信息
可以使用 ngx.req.get_headers() 方法来获取请求头信息:
local headers = ngx.req.get_headers()
ngx.say("user-agent: ", headers["User-Agent"])条件语句的使用:
location /swagger/{
set $isproxy 0;
set_by_lua $isproxy '
return 0
';
if ($isproxy = 1)
{
return 403;
proxy_pass http://127.0.0.1:8023;
}
if ($isproxy = 0)
{
content_by_lua_block {
ngx.say("hello")
}
}
}限流的使用:
lua_code_cache on;
lua_shared_dict my_limit_count_store 10M;
server
{
listen 8024;
index index.html index.htm default.htm default.html;
location /limit/conn {
access_by_lua_block {
ngx.header["Content-Type"] = "text/json"
local limit_count = require "resty.limit.count"
local cjson = require "cjson"
-- 1秒内只能有20个请求
local lim, err = limit_count.new("my_limit_count_store", 20, 1)
if not lim then
ngx.say(cjson.encode({code=-1}))
return
end
local key = ngx.var.uri
local delay, err = lim:incoming(key, true)
if not delay then
if err == "rejected" then
ngx.say(cjson.encode({code=-1}))
return
end
ngx.log(ngx.ERR, "failed to limit req: ", err)
return ngx.exit(500)
end
ngx.say(key)
}
}
}