spring cloud gateway中解决第一次请求失败的问题

时间:2022-10-17 20:07:53

在项目中使用spring cloud gateway之后中,发现第一次路由请求都会失败。

百度了一下,知道是hystix timeout的问题:

即Hystrix默认的超时时间是1秒,如果超过这个时间尚未响应,将会进入fallback代码。

而首次请求往往会比较慢(因为Spring的懒加载机制,要实例化一些类),这个响应时间可能就大于1秒了。

一般有三种解决方案:

1)延长hystix的连接超时时间,默认时间是1秒

//在Fegion服务的application配置文件中添加一下配置:
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds:5000


2)禁用hystix的超时时间

//在Fegion服务的application配置文件中添加一下配置:
hystrix.command.default.execution.timeout.enabled: false


3)直接禁用hystix

//在Fegion服务的application配置文件添加如下配置信息:
feign.hystrix.enabled: false

 

个人感觉第2/3方案都太简单粗暴了,后面也会出现其他问题,所以先试试第1个方案。

为了对hystrix timeout了解更清楚,避免碰到其他坑,再次百度,总结hystrix配置如下

spring cloud gateway中解决第一次请求失败的问题

最终解决方案,如果配置文件的版本基本如方案1所写(并未测试),由于我的网关使用代码编写的,最终如下

   @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        Builder result=builder.routes();
        //services列表
        for (int i = 0; i < services.length; i++) {
            String service = services[i];
            result=result.route(p -> p
                    .path("/"+service+"/**")
                    .filters(f -> f
                        .hystrix(config -> config   // 对path()指定的请求使用熔断器
                                 .setName("hystrix-"+service)   // 熔断器的名字
                                 .setFallbackUri("forward:/fallback")// 熔断
                                 .setSetter(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(service))
                                         .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                                         .withExecutionTimeoutInMilliseconds(5000))//超时
                                 ))) 
                    .uri("lb://"+service)); // 将请求路由到指定目标, lb开头是注册中心中的服务
        }
        return result.build();
    }