SpringMvc 之 接口超时
在日常开发过程中,经常会遇到接口超时的问题,所以本人在这里做一些解决方案的总结,希望可以对大家有用。
一、springmvc配置Http会话超时
1、application.properties中配置会话超时(默认30分钟)
server.servlet.session.timeout=60s
2、通过配置 EmbeddedServletContainerCustomizer 的bean进行实现
@Configuration public class WebConfiguration { @Bean public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer() { return new EmbeddedServletContainerCustomizer() { @Override public void customize(ConfigurableEmbeddedServletContainer container) { container.setSessionTimeout(2, TimeUnit.MINUTES); } }; } }
二、springmvc配置接口访问超时
1、application.properties中加配置
#这是 Tomcat 服务器的超时设置,主要处理 TCP 层面的连接请求,单位ms
server.tomcat.connection-timeout=120000
# Spring MVC 的超时设置。它控制的是从 Controller 方法开始处理请求到响应结果被写入响应体的时间,120000ms 即 120s
spring.mvc.async.request-timeout=120000
2、通过配置类实现
@Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void configureAsyncSupport(final AsyncSupportConfigurer configurer) { configurer.setDefaultTimeout(120000); configurer.registerCallableInterceptors(timeoutInterceptor()); } @Bean public TimeoutCallableProcessingInterceptor timeoutInterceptor() { return new TimeoutCallableProcessingInterceptor(); } }
或者直接自定义嵌入tomcat配置(springboot2.x):
import org.apache.catalina.connector.Connector; import org.apache.coyote.http11.Http11NioProtocol; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.context.annotation.Bean; import java.nio.charset.Charset; @SpringBootConfiguration public class WebServerConfiguration { @Bean public ConfigurableServletWebServerFactory webServerFactory() { TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); factory.setPort(8888); factory.setUriEncoding(Charset.forName("utf-8"));//编码 factory.addConnectorCustomizers(new MyTomcatConnectorCustomizer()); return factory; } class MyTomcatConnectorCustomizer implements TomcatConnectorCustomizer { @Override public void customize(Connector connector) { Http11NioProtocol handler = (Http11NioProtocol)connector.getProtocolHandler(); handler.setAcceptCount(1000);// 排队数 handler.setMaxConnections(1000);// 最大连接数 handler.setMaxThreads(500);// 线程池的最大线程数 handler.setMinSpareThreads(50);// 最小线程数 handler.setConnectionTimeout(20000);// 超时时间 20S } } }
@Bean public TomcatServletWebServerFactory tomcatFactory() { return new TomcatServletWebServerFactory() { @Override protected void customizeConnector(Connector connector) { super.customizeConnector(connector); // 设置 Tomcat 的 Socket 参数(需谨慎使用) connector.setProperty("socket.soTimeout", "60000"); // 60秒 connector.setProperty("socket.keepAlive", "true"); } }; }
三、外部tomcat的超时设置
tomcat的配置文件server.xml中设置超时时间,默认是20000ms 即 20s
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="120000" redirectPort="8443" />
四、springcloud 微服务调用超时:
Ribbon默认连接超时时间是1秒,读取数据超时时间为1秒。
Feign的默认是连接超时时间10秒、读超时时间60秒。
ribbon: ReadTimeout: 100000 #读超时时长ms,指的是业务处理时间 ConnectTimeout: 100000 #连接超时时长ms MaxAutoRetries: 0 #第一次访问失败后,对同一端点的重试次数 MaxAutoRetriesNextServer: 1 #第一次访问失败后,对其他端点的重试次数 OkToRetryOnAllOperations: false # 是否所有操作都重试
feign: client: config:
#默认全局的超时时间,ms default: connectTimeout: 5000 readTimeout: 5000
#服务名为 order-service 的服务超时时间 order-service: connectTimeout: 1000 readTimeout: 6000
更细粒度的区分也可以通过contxtId进行区分。在FeignClient申明中指定contextId属性。
@FeignClient( name = "order-service", url = "/orders", path = "/list", fallback = OrderFallbackService.class,contextId = "order-client" )
feign: client: config: #默认全局的超时时间,ms default: connectTimeout: 5000 readTimeout: 5000 #contextId 名为 order-client 的feign调用超时时间 order-client: connectTimeout: 1000 readTimeout: 6000
contextId不与服务名字重复,feign优先按照contextId进行查找自定义超时配置,无contextId的时候使用服务名字查找。
新版本的springcloud如果进行以上配置不生效时,通过下面的形式配置:
spring: cloud: openfeign: client: config: default: connectTimeout: 50000 readTimeout: 50000
springcloud 中 feign 如果没有配置超时时间的话会使用ribbon的超时时间,所以可以只配置ribbon的超时间就可以了,如果配置了feign,则ribbon使用feign的配置。
hystrix 超时时间超时配置要大于feign和ribbon的超时时间,如果有接口重试则hystrix超时时间需要乘以重试次数。
# 设置 hystrix 超时时间 feign: hystrix: enabled: true hystrix: command: default: execution: isolation: thread: timeoutInMilliseconds: 6000
五、Socket 连接超时
通用Socket设置:
Socket socket = new Socket(); socket.setSoTimeout(5000); // 设置已建立连接超时时间为5秒,表示在没有读取到任何数据时,Socket会等待的时间长度 socket.connect(new InetSocketAddress("远程主机地址", 端口号),2000); //设置建立连接超时时间为2s
SocketChannel设置:
SocketChannel socketChannel = SocketChannel.open();
//channel.socket().connect(new InetSocketAddress("localhost", 8080), timeout); socketChannel.connect(new InetSocketAddress("localhost", 8080)); // 设置读取超时为5秒 socketChannel.configureBlocking(false); socketChannel.socket().setSoTimeout(5000);
netty超时设置:
ServerBootstrap bootstrap = new ServerBootstrap(); // 设置连接超时为5秒 bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000); // 设置读取超时为60秒 bootstrap.childOption(ChannelOption.SO_TIMEOUT, 60000);
六、Nginx的设置
在Nginx的配置文件nginx.conf中设置转发超时时间,未设置时Nginx响应时间默认60秒。
http头部的 keepalive_timeout 、client_header_timeout 、client_body_timeout 、send_timeout、proxy_connect_timeout、proxy_send_timeout、proxy_read_timeout
server代码块中也可单独设置 proxyTimeout ,单位为秒。
http {
proxy_send_timeout 10s;
proxy_connect_timeout 60s; keepalive_timeout 60s; #连接超时时间,服务器将会在这个时间后关闭连接 send_timeout 60s; #发送超时时间 client_header_timeout 60s; #请求头的超时时间 client_body_timeout 60s; #请求体的读超时时间 #业务系统的配置 server { listen 80; server_name localhost; location / { proxy_pass http://127.0.0.1:80/web/; proxy_read_timeout 10s; # 等候后端服务器响应时间 秒 } } }
nginx的时间单位:
ms milliseconds s seconds m minutes h hours d days w weeks M months, 30 days y years, 365 days
六、dubbo中的接口超时
dubbo这样的Jave RPC框架,除了以上设置后,还需要在application-*.yml(或者xml中)配置消费端的默认的响应超时时长。
dubbo: application: name: web consumer: timeout: 120000 #默认超时时间120s
原创文章,引用和转载注明出处:https://www.cnblogs.com/hewei-blogs/articles/17336914.html
本文来自博客园,作者:蓝迷梦,转载请注明原文链接:https://www.cnblogs.com/hewei-blogs/articles/17336914.html

浙公网安备 33010602011771号