因此,當我在我編寫的應用程式中本地測試諸如 Ajax 之類的東西時,我經常喜歡使用語句在伺服器端腳本中添加延遲sleep
。它有助於模擬慢速連接等。
有沒有辦法直接在 Nginx 配置中指定類似的延遲行為,該行為適用於它所提供的平面 HTML 檔案?
我知道您可以在網路層級進行類似的延遲模擬(請參閱這裡)但它看起來很混亂,而且對我來說從來沒有很好的效果。
答案1
答案2
更詳細地解釋如何使用 echo 模組:
如果您從基本配置開始,載入靜態文件和 PHP 文件,如下所示:
location ~ \.php$ {
include fastcgi.conf;
fastcgi_pass php;
}
然後可以將其轉換為類似的內容,以增加靜態請求和 PHP 請求的延遲:
# Static files
location / {
echo_sleep 5;
echo_exec @default;
}
location @default {}
# PHP files
location ~ \.php$ {
echo_sleep 5;
echo_exec @php;
}
location @php {
include fastcgi.conf;
fastcgi_pass php;
}
這顯然可以修改為您想要的任何內容。基本上,將每個位置區塊移動到一個命名的@location 中。然後在原來的位置區塊中使用echo_sleep
and 。echo_exec
答案3
我想添加到阿斯特洛克的回答如果您想簡單地回复return
,請注意有一個警告:您必須使用after來延遲回應,echo
而不是標準return
指令,如下所示:echo_sleep
location = /slow-reply {
echo_sleep 5.0;
#return 200 'this response would NOT be delayed!';
echo 'this text will come in response body with HTTP 200 after 5 seconds';
}
(在 openresty/1.7.10.2 上測試)
答案4
以下 python 腳本對我來說效果很好,恕我直言值得分享。
#!/usr/bin/env python
# Includes
import getopt
import sys
import os.path
import subprocess
from http.server import HTTPServer
from http.server import BaseHTTPRequestHandler
import socketserver
import time
######## Predefined variables #########
helpstring = """Usage: {scriptname} args...
Where args are:
-h, --help
Show help
-p PORTNUMBER
Port number to run on
-d delay-in-seconds
How long to wait before responding
"""
helpstring = helpstring.format(scriptname=sys.argv[0])
def beSlow(seconds):
time.sleep(float(seconds))
######## Functions and classes #########
class SlowserverRequestHandler(BaseHTTPRequestHandler):
def do_GET(s):
if s.path == "/slow":
# Check status
# Assume fail
code = 200
status = ""
# Be slow for a while
beSlow(seconds)
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
s.wfile.write(b"I'm a slow response LOL\n")
else:
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
s.wfile.write(b"slowserver - reporting for duty. Slowly...\n")
# Parse args
try:
options, remainder = getopt.getopt(sys.argv[1:], "hp:d:", ['help'])
except:
print("Invalid args. Use -h or --help for help.")
raise
sys.exit(1)
HTTPPORT = 8000
for opt, arg in options:
if opt in ('-h', '--help'):
print(helpstring)
sys.exit(0)
elif opt in ('-p'):
HTTPPORT = int(arg)
elif opt in ('-d'):
seconds = arg
# Start HTTP service
server_class=HTTPServer
handler_class=SlowserverRequestHandler
server_address = ('', HTTPPORT)
httpd = server_class(server_address, handler_class)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()