The number of milliseconds this Connector will wait, after accepting a connection, for the request URI line to be presented. Use a value of -1 to indicate no (i.e. infinite) timeout. The default value is 60000 (i.e. 60 seconds) but note that the standard server.xml that ships with Tomcat sets this to 20000 (i.e. 20 seconds). Unless disableUploadTimeout is set to false, this timeout will also be used when reading the request body (if any).
@FeignClient(name = "wood-system",contextId = "wood-system-holiday-feign")
public interface HolidayFeign {
@GetMapping("/api/holiday/{id}")
Result selectOne(Request.Options options,@PathVariable Long id);
@PostMapping("/api/holiday/page/{pageNum}/{pageSize}")
Result
调用的时候new 一下Options对象
@Resource
private HolidayFeign holidayFeign;
@GetMapping("{id}")
public Result selectOne(@PathVariable Long id) {
Request.Options options = new Request.Options(10, TimeUnit.SECONDS, 10, TimeUnit.SECONDS, true);
return holidayFeign.selectOne(options, id);
}
@PostMapping("/page/{pageNum}/{pageSize}")
public Result
-- 默认是0,即无限
select @@max_execution_time;
show variables like 'max_execution_time';
-- 全局设置
SET GLOBAL MAX_EXECUTION_TIME=1000;
-- 对某个session设置
SET SESSION MAX_EXECUTION_TIME=1000;
-- 单独设定sql设置超时时间
SELECT /*+ MAX_EXECUTION_TIME(1000) */ sleep(3), a.* from project_info a;
sql执行超时抛出错误:Query execution was interrupted, maximum statement execution time exceeded。
数据库事务超时
# 默认是50秒
select @@innodb_lock_wait_timeout;
SHOW VARIABLES LIKE 'innodb_lock_wait_timeout';
set innodb_lock_wait_timeout=30;
set global innodb_lock_wait_timeout=30;
/**
* Defaults to using HTTP/1.1 NIO implementation.
*/
public Connector() {
this("HTTP/1.1");
}
public Connector(String protocol) {
boolean apr = AprStatus.getUseAprConnector() && AprStatus.isInstanceCreated()
&& AprLifecycleListener.isAprAvailable();
ProtocolHandler p = null;
try {
p = ProtocolHandler.create(protocol, apr);
} catch (Exception e) {
log.error(sm.getString(
"coyoteConnector.protocolHandlerInstantiationFailed"), e);
}
if (p != null) {
protocolHandler = p;
protocolHandlerClassName = protocolHandler.getClass().getName();
} else {
protocolHandler = null;
protocolHandlerClassName = protocol;
}
// Default for Connector depends on this system property
setThrowOnFailure(Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE"));
}
ProtocolHandler
public static ProtocolHandler create(String protocol, boolean apr)
throws ClassNotFoundException, InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
if (protocol == null || "HTTP/1.1".equals(protocol)
|| (!apr && org.apache.coyote.http11.Http11NioProtocol.class.getName().equals(protocol))
|| (apr && org.apache.coyote.http11.Http11AprProtocol.class.getName().equals(protocol))) {
if (apr) {
return new org.apache.coyote.http11.Http11AprProtocol();
} else {
return new org.apache.coyote.http11.Http11NioProtocol();
}
} else if ("AJP/1.3".equals(protocol)
|| (!apr && org.apache.coyote.ajp.AjpNioProtocol.class.getName().equals(protocol))
|| (apr && org.apache.coyote.ajp.AjpAprProtocol.class.getName().equals(protocol))) {
if (apr) {
return new org.apache.coyote.ajp.AjpAprProtocol();
} else {
return new org.apache.coyote.ajp.AjpNioProtocol();
}
} else {
// Instantiate protocol handler
Class> clazz = Class.forName(protocol);
return (ProtocolHandler) clazz.getConstructor().newInstance();
}
}
Http11NioProtocol
public class Http11NioProtocol extends AbstractHttp11JsseProtocol {
private static final Log log = LogFactory.getLog(Http11NioProtocol.class);
public Http11NioProtocol() {
super(new NioEndpoint());
}
}
public abstract class AbstractHttp11JsseProtocol
extends AbstractHttp11Protocol {
public AbstractHttp11JsseProtocol(AbstractJsseEndpoint endpoint) {
super(endpoint);
}
... ...
}
public abstract class AbstractHttp11Protocol extends AbstractProtocol {
... ...
public AbstractHttp11Protocol(AbstractEndpoint endpoint) {
super(endpoint);
setConnectionTimeout(Constants.DEFAULT_CONNECTION_TIMEOUT);
ConnectionHandler cHandler = new ConnectionHandler(this);
setHandler(cHandler);
getEndpoint().setHandler(cHandler);
}
public void setConnectionTimeout(int timeout) {
endpoint.setConnectionTimeout(timeout);
}
}
public final class Constants {
public static final int DEFAULT_CONNECTION_TIMEOUT = 60000;
... ...
}
AbstractEndpoint
public abstract class AbstractEndpoint {
... ...
public static long toTimeout(long timeout) {
// Many calls can't do infinite timeout so use Long.MAX_VALUE if timeout is 0) ? timeout : Long.MAX_VALUE;
}
/**
* Socket timeout.
*
* @return The current socket timeout for sockets created by this endpoint
*/
public int getConnectionTimeout() { return socketProperties.getSoTimeout(); }
public void setConnectionTimeout(int soTimeout) { socketProperties.setSoTimeout(soTimeout); }
}
/**
*Properties that can be set in the element in server.xml.
*All properties are prefixed with "socket." and are currently only working for the Nio connector
*/
public class SocketProperties {
...
/**
* SO_TIMEOUT option. default is 20000.
*/
protected Integer soTimeout = Integer.valueOf(20000);
}
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
9.1.6 SpringBoot创建tomcat服务
入口 refresh()
//org.springframework.context.support.AbstractApplicationContext#refresh
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
......
try {
....
// Initialize other special beans in specific context subclasses.
onRefresh();
....
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
}
}
}
//org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#onRefresh
@Override
protected void onRefresh() {
super.onRefresh();
try {
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}
//org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#createWebServer
private void createWebServer() {
WebServer webServer = this.webServer;
ServletContext servletContext = getServletContext();
if (webServer == null && servletContext == null) {
ServletWebServerFactory factory = getWebServerFactory();
this.webServer = factory.getWebServer(getSelfInitializer());
}
else if (servletContext != null) {
try {
getSelfInitializer().onStartup(servletContext);
}
catch (ServletException ex) {
throw new ApplicationContextException("Cannot initialize servlet context", ex);
}
}
initPropertySources();
}
//org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory#getWebServer
@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
if (this.disableMBeanRegistry) {
Registry.disableRegistry();
}
Tomcat tomcat = new Tomcat();
File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
tomcat.setBaseDir(baseDir.getAbsolutePath());
//初始化
Connector connector = new Connector(this.protocol);
connector.setThrowOnFailure(true);
tomcat.getService().addConnector(connector);
customizeConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
configureEngine(tomcat.getEngine());
for (Connector additionalConnector : this.additionalTomcatConnectors) {
tomcat.getService().addConnector(additionalConnector);
}
prepareContext(tomcat.getHost(), initializers);
return getTomcatWebServer(tomcat);
}
/**
* Finish the initialization of this context's bean factory,
* initializing all remaining singleton beans.
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
... ...
// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();
}
public T getBean(String name, @Nullable Class requiredType, @Nullable Object... args)
throws BeansException {
return doGetBean(name, requiredType, args, false);
}
protected T doGetBean(
String name, @Nullable Class requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
... ...
return createBean(beanName, mbd, args);
... ...
}
/**
* Central method of this class: creates a bean instance,
* populates the bean instance, applies post-processors, etc.
* @see #doCreateBean
*/
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
...
return beanInstance;
... ...
}
/**
* Actually create the specified bean. Pre-creation processing has already happened
* at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
*
Differentiates between default Bean instantiation, use of a
* factory method, and autowiring a constructor.
* @param beanName the name of the bean
* @param mbd the merged bean definition for the bean
* @param args explicit arguments to use for constructor or factory method invocation
* @return a new instance of the bean
* @throws BeanCreationException if the bean could not be created
* @see #instantiateBean
* @see #instantiateUsingFactoryMethod
* @see #autowireConstructor
*/
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
... ...
Object bean = instanceWrapper.getWrappedInstance();
... ...
// Initialize the bean instance.
Object exposedObject = bean;
// Populate the bean instance in the given BeanWrapper with the property values from the bean definition.
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
... ...
}
/**
* Initialize the given bean instance, applying factory callbacks
* as well as init methods and bean post processors.
*
Called from {@link #createBean} for traditionally defined beans,
* and from {@link #initializeBean} for existing bean instances.
* @param beanName the bean name in the factory (for debugging purposes)
* @param bean the new bean instance we may need to initialize
* @param mbd the bean definition that the bean was created with
* (can also be {@code null}, if given an existing bean instance)
* @return the initialized bean instance (potentially wrapped)
* @see BeanNameAware
* @see BeanClassLoaderAware
* @see BeanFactoryAware
* @see #applyBeanPostProcessorsBeforeInitialization
* @see #invokeInitMethods
* @see #applyBeanPostProcessorsAfterInitialization
*/
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
public abstract class TcpClient {
... ...
/**
* Block the {@link TcpClient} and return a {@link Connection}. Disposing must be
* done by the user via {@link Connection#dispose()}. The max connection
* timeout is 45 seconds.
*
* @return a {@link Mono} of {@link Connection}
*/
public final Connection connectNow() {
return connectNow(Duration.ofSeconds(45));
}
/**
* Block the {@link TcpClient} and return a {@link Connection}. Disposing must be
* done by the user via {@link Connection#dispose()}.
*
* @param timeout connect timeout
*
* @return a {@link Mono} of {@link Connection}
*/
public final Connection connectNow(Duration timeout) {
Objects.requireNonNull(timeout, "timeout");
try {
return Objects.requireNonNull(connect().block(timeout), "aborted");
}
catch (IllegalStateException e) {
if (e.getMessage().contains("blocking read")) {
throw new IllegalStateException("TcpClient couldn't be started within "
+ timeout.toMillis() + "ms");
}
throw e;
}
}
}
参数覆盖
在 GatewayAutoConfiguration中
public class GatewayAutoConfiguration {
... ...
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(HttpClient.class)
protected static class NettyConfiguration {
... ...
@Bean
@ConditionalOnMissingBean
public HttpClient gatewayHttpClient(HttpClientProperties properties,
List customizers) {
HttpClient httpClient = HttpClient.create(connectionProvider)
...
.tcpConfiguration(tcpClient -> {
if (properties.getConnectTimeout() != null) {
tcpClient = tcpClient.option(
ChannelOption.CONNECT_TIMEOUT_MILLIS,
properties.getConnectTimeout());
}
... ...
return httpClient;
}
... ...
}
}
public static final int DEFAULT_READ_TIMEOUT = 5000;
public static final int DEFAULT_CONNECTION_MANAGER_TIMEOUT = 2000;
public static final int DEFAULT_CONNECT_TIMEOUT = 2000;