系统学习 中间件学习路径:日志、消息、网关与数据高可用

varnish

Varnish HTTP 缓存服务

补充说明

Varnish 是 HTTP 反向代理缓存,用 VCL 描述缓存策略。它适合静态内容和可缓存的 API 响应,能显著降低后端压力。

常用示例

varnishd -f /etc/varnish/default.vcl -s malloc,2g -a :80
varnishd -C -f /etc/varnish/default.vcl
varnishadm -S /etc/varnish/secret -T 127.0.0.1:6082
varnishadm 'vcl.list'
varnishadm 'backend.list'
varnishadm 'ban req.url ~ "^/old"'
varnishlog
varnishstat
varnishncsa
varnishreload

VCL 要点:

backend default {
  .host = "127.0.0.1";
  .port = "8080";
}

sub vcl_recv {
  if (req.method != "GET" && req.method != "HEAD") {
    return (pass);
  }
  if (req.url ~ "^/api/") {
    return (pass);
  }
}

sub vcl_backend_response {
  set beresp.ttl = 60s;
}

易错点与排错

相关命令

参考链接

读完自测

合上页面,先回答,再展开对照。

  1. 怎样在启动前发现 VCL 语法错误?
  2. 带 cookie 或认证的响应默认会被缓存吗?需要怎么做?
  3. 内存后端 malloc 大小设置不足会有什么表现?
答案
  1. 用 varnishd -C 编译检查 VCL。
  2. 默认不缓存;需要显式策略并在 vcl_recv 中处理。
  3. 缓存空间不足会导致频繁淘汰。
微信小程序码:扫码打开命令速查小程序

小程序版

微信扫码,随时查命令