AsyncHTTPClient 透傳請求/回應、Header 重寫在微服務架構中,API 閘道需將客戶端請求代理至上游服務。Tornado 非阻塞 I/O 模型天然適合代理場景。本文實現 ProxyHandler:透傳方法/Body/Header、重寫 Host、流式回應、錯誤處理、支援 GET/POST,核心代碼不足 100 行。
import logging
import tornado.web, tornado.httpserver, tornado.ioloop, tornado.httpclient, tornado.options
from tornado.web import HTTPError, asynchronous
from tornado.httpclient import HTTPRequest
from tornado.options import define, options
try:
from tornado.curl_httpclient import CurlAsyncHTTPClient as AsyncHTTPClient
except ImportError:
from tornado.simple_httpclient import SimpleAsyncHTTPClient as AsyncHTTPClient
define("port", default=8888, type=int)
define("api_protocol", default="http")
define("api_host", default="feilong.me")
define("api_port", default="80")
define("debug", default=True, type=bool)
class ProxyHandler(tornado.web.RequestHandler):
@asynchronous
def get(self):
if options.debug:
return self.post()
raise HTTPError(405)
@asynchronous
def post(self):
protocol = options.api_protocol
host = options.api_host
port = "" if options.api_port == "80" else ":%s" % options.api_port
uri = self.request.uri
url = "%s://%s%s%s" % (protocol, host, port, uri)
# 重寫 Host,保留其他 Header
headers = dict(self.request.headers)
headers["Host"] = host
try:
AsyncHTTPClient().fetch(
HTTPRequest(
url=url,
method="POST",
body=self.request.body,
headers=headers,
follow_redirects=False
),
self._on_proxy
)
except tornado.httpclient.HTTPError as e:
if hasattr(e, 'response') and e.response:
self._on_proxy(e.response)
else:
logging.error("Tornado signalled HTTPError %s", e)
def _on_proxy(self, response):
if response.error and not isinstance(response.error, tornado.httpclient.HTTPError):
raise HTTPError(500)
self.set_status(response.code)
for h in ("Date", "Cache-Control", "Server", "Content-Type", "Location"):
v = response.headers.get(h)
if v:
self.set_header(h, v)
if response.body:
self.write(response.body)
self.finish()
def main():
tornado.options.parse_command_line()
app = tornado.web.Application([(r"/.*", ProxyHandler)])
tornado.httpserver.HTTPServer(app).listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
python proxy.py --port=8888 --api_host=example.com
# 訪問 https://localhost:8888/ → 顯示 example.com 內容
AsyncHTTPClient:單執行緒支援高併發代理,無執行緒池開銷。Date/Cache-Control/Server/Content-Type/Location,避免洩露上游內部 Header(Set-Cookie、X-Powered-By 等)。follow_redirects=False:由代理端決定是否追蹤重導向,避免循環或洩露內部 URL。api_host 改為列表,輪詢/隨機選擇hystrix 或自實現)websocket_ping_interval、WebSocketHandler)| 方案 | 特點 |
|---|---|
Nginx proxy_pass | 高效能、配置式、無業務邏輯 |
| Kong / APISIX / Traefik | 全功能 API 閘道、插件生態、可視化 |
| Envoy + gRPC | Service Mesh 側車、L7 可觀測 |
| Tornado 代理(本文) | 邏輯可編程、快速原型、整合既有 Tornado 服務 |
Tornado 代理適合「需在代理層注入業務邏輯」的場景;純流量轉發請用 Nginx/Envoy 等基礎設施層方案。