如何告诉 Nginx 在提供资产之前等待几秒钟?

如何告诉 Nginx 在提供资产之前等待几秒钟?

因此,当我在本地测试我编写的应用程序中 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和。echo_exec

答案3

我想补充astlock 的回答如果你想用一个简单的回复return,那么请注意有一个警告:你必须使用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()

来源(gist.github.com)

相关内容