nginx - POST 响应缓存在 nginx 中不起作用
问题描述
我的任务是使用 nginx 实现微缓存策略,即缓存一些 POST 端点的响应几秒钟。
在我的http
部分中,nginx.conf
我有以下内容:
proxy_cache_path /tmp/cache keys_zone=cache:10m levels=1:2 inactive=600s max_size=100m;
然后我location
有server
:
location /my-url/ {
root dir;
client_max_body_size 50k;
proxy_cache cache;
proxy_cache_valid 10s;
proxy_cache_methods POST;
proxy_cache_key "$request_uri|$request_body";
proxy_ignore_headers Vary;
add_header X-Cached $upstream_cache_status;
proxy_pass http://my-upstream;
}
位于my-upstream
输出的应用程序Cache-Control: max-age=10
,如果我理解正确的话,应该使响应可缓存。
但是当我在短时间内(不到 10 秒)使用 curl 发出重复请求时
curl -v --data "a=b&c=d" https://my-host/my-url/1573
所有这些都到达后端(根据后端日志)。还有,X-Cached
总是MISS
。
请求和响应如下:
> POST /my-url/1573 HTTP/1.1
> Host: my-host
> User-Agent: curl/7.47.0
> Accept: */*
> Content-Length: 113
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 113 out of 113 bytes
< HTTP/1.1 200 OK
< Server: nginx
< Date: Tue, 08 May 2018 07:16:10 GMT
< Content-Type: text/html;charset=utf-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< Keep-Alive: timeout=60
< Vary: Accept-Encoding
< X-XSS-Protection: 1
< X-Content-Type-Options: nosniff
< Strict-Transport-Security: max-age=31536000
< Cache-Control: max-age=10
< Content-Language: en-US
< X-Cached: MISS
所以缓存不起作用。
- 我在这里做错了什么?
- nginx 中是否有任何日志记录工具可以查看为什么它选择不缓存响应?
解决方案
事实证明,以下指令(全局定义)阻止了缓存工作:
proxy_buffering off;
当我在location
config with下覆盖它时proxy_buffering on;
,缓存开始工作。
因此,要使缓存与 POST 请求一起使用,我们必须执行以下操作:
Cache-Control: public, max-age=10
服务器上的输出标头- 在nginx中添加
proxy_cache_path
config和location
config(问题文中给出示例) - 确保这
proxy_buffering
是on
我们想要启用缓存的位置。
推荐阅读
- c - 全局 SDL_Renderer* 在函数调用时发生变化
- excel-formula - 如何使用公式在字母前添加空格
- php - PHP Docker 映像安装事件扩展失败
- dask - 如何在 dask 数据帧中按移位乘法进行分组
- google-sheets - 无法读取来自 Google 表格的 Bigquery 表(誓言/范围错误)
- c++ - 使用 nlohmann json 在文件中保存 json 数据时获取空值
- c# - 我可以获得Excel电子表格行的实际Excel行号(不是顺序计算的数字)
- pyspark - 使用 pyspark 随机选择列
- opengl - 关于glPolygonOffset公式的问题
- python - 为什么PYNPUT鼠标监听中的IF判断会被操作两次?