一个简单的选项是在继续进行后端进程时尽快终止客户端连接。
server {
location /test {
# map 402 error to backend named location
error_page 402 = @backend;
# pass request to backend
return 402;
}
location @backend {
# close client connection after 1 second
# Not bothering with sending gif
send_timeout 1;
# Pass the request to the backend.
proxy_pass http://127.0.0.1:8080;
}
}
上面的选项虽然简单,但可能会导致客户端在连接断开时收到错误消息。ngx.say 指令将确保发送“200 OK”标头,并且由于它是异步调用,因此不会阻止任何事情。这需要 ngx_lua 模块。
server {
location /test {
content_by_lua '
-- send a dot to the user and transfer request to backend
-- ngx.say is an async call so processing continues after without waiting
ngx.say(".")
res = ngx.location.capture("/backend")
';
}
location /backend {
# named locations not allowed for ngx.location.capture
# needs "internal" if not to be public
internal;
# Pass the request to the backend.
proxy_pass http://127.0.0.1:8080;
}
}
一个更简洁的基于 Lua 的选项:
server {
location /test {
rewrite_by_lua '
-- send a dot to the user
ngx.say(".")
-- exit rewrite_by_lua and continue the normal event loop
ngx.exit(ngx.OK)
';
proxy_pass http://127.0.0.1:8080;
}
}
绝对是一个有趣的挑战。