首页 > 解决方案 > 使用 Spring 云网关和 Nginx 作为反向代理的网关超时

问题描述

我为我的应用程序创建了一个 API 网关,它将充当其他微服务的前端控制器。在我的生产设置中,我使用 Nginx 作为网关的反向代理

API 网关在 8080 端口上运行

Nginx 配置如下:

网关-api.conf:

server {
    listen 80;
    server_name api.example.com;
    location / {
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_pass http://localhost:30010/;
        keepalive_timeout 500s;
    }
    keepalive_timeout 500s;
    access_log /var/log/nginx/api.log;  
    error_log /var/log/nginx/api_error.log;
}

nginx.conf 中的超时设置:

proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 300;
send_timeout 300;

Spring Cloud 网关 gradle 文件:

compile('org.springframework.cloud:spring-cloud-starter-gateway')
 compile('org.springframework.cloud:spring-cloud-starter-openfeign')
 compile("org.springframework.boot:spring-boot-starter-actuator")
 compile('org.springframework.boot:spring-boot-starter-security')

springBootVersion=2.0.3.RELEASE
springDMPVersion=1.0.4.RELEASE
springPlatformBomVersion=Cairo-SR2
springCloudVersion=Finchley.RELEASE

网关应用:

@SpringBootApplication
@ComponentScan(basePackages = {"com.example"})
@EntityScan(basePackages = {"com.example"})
@EnableFeignClients(basePackages = "com.example")
public class GatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}

问题陈述:

在我的一个微服务中,一个 REST API 需要 3 多分钟才能完成。如果我通过 调用这个 API ,它会在 1 分钟后nginx(api.example.com)失败并给出 HTTP 状态 504。

卷曲:

curl --request GET \
  --url http://api.example.com/hellomicroservice/api/take/moretime

错误:

504 Timeout while reading the response from Server

nginx 或 API 网关中没有错误日志。

从 nginx 访问日志:

203.129.213.102 - - [01/Apr/2019:08:14:33 +0000] "GET hellomicroservice/api/take/moretime HTTP/1.1" 499 0 "-" "PostmanRuntime/7.3.0"

但是当我直接向网关(在网关端口 8080 上)调用相同的 API 时,请求被成功处理。

curl 与网关端口:

curl --request GET \
  --url http://api.example.com:8080/hellomicroservice/api/take/moretime

编辑:

如果我将 Nginx 超时设置应用为小于 60 秒(例如 30 秒),则请求会在指定的时间间隔内超时。但是如果我将 Nginx 超时设置为超过 60 秒,让我们设置为 300 秒,则请求会在 60 秒后超时。

标签: javanginxspring-cloudnginx-reverse-proxyspring-cloud-gateway

解决方案


我想这是由于许多其他事情而可能发生的问题之一。这是一个对我有用的解决方案(我也遇到了错误/var/log/nginx/error.log

2020/12/30 21:47:47 [错误] 26765#26765:* 13064 上游超时(110:连接超时)同时连接到上游,客户端:XXX,服务器:example.com,请求:“GET /eshop HTTP/1.0”,上游:“http://[::1]:8080/error_50x.html”,主机:“example.com”

奇怪的是,这并没有发生在我的笔记本电脑上,而只是发生在我的服务器上。所以我检查了 IP,结果可能是因为缺少 ::1 地址。当我将它添加到lo网络设备时,我无法复制超时。

sudo ip a add ::1/128 dev lo

下一步:(这是我的理解,我不是 100% 确定这一点:)此外,由于保持与 localhost Java 服务的连接的开销似乎高于仅在发出另一个请求时断开该连接并再次连接,建议对代理使用以下设置(在您的 nginx 站点 .conf 中):

proxy_http_version 1.1;
proxy_set_header Connection "";

https://stackoverflow.com/a/10396874/3223505


推荐阅读