聊聊tomcat的connection-timeout

本文主要研究一下tomcat的connection-timeout

ServerProperties.Tomcat

org/springframework/boot/autoconfigure/web/ServerProperties.java

	public static class Tomcat {

		/**
		 * Access log configuration.
		 */
		private final Accesslog accesslog = new Accesslog();

		/**
		 * Thread related configuration.
		 */
		private final Threads threads = new Threads();

		/**
		 * Tomcat base directory. If not specified, a temporary directory is used.
		 */
		private File basedir;

		/**
		 * Delay between the invocation of backgroundProcess methods. If a duration suffix
		 * is not specified, seconds will be used.
		 */
		@DurationUnit(ChronoUnit.SECONDS)
		private Duration backgroundProcessorDelay = Duration.ofSeconds(10);

		/**
		 * Maximum size of the form content in any HTTP post request.
		 */
		private DataSize maxHttpFormPostSize = DataSize.ofMegabytes(2);

		/**
		 * Maximum amount of request body to swallow.
		 */
		private DataSize maxSwallowSize = DataSize.ofMegabytes(2);

		/**
		 * Whether requests to the context root should be redirected by appending a / to
		 * the path. When using SSL terminated at a proxy, this property should be set to
		 * false.
		 */
		private Boolean redirectContextRoot = true;

		/**
		 * Whether HTTP 1.1 and later location headers generated by a call to sendRedirect
		 * will use relative or absolute redirects.
		 */
		private boolean useRelativeRedirects;

		/**
		 * Character encoding to use to decode the URI.
		 */
		private Charset uriEncoding = StandardCharsets.UTF_8;

		/**
		 * Maximum number of connections that the server accepts and processes at any
		 * given time. Once the limit has been reached, the operating system may still
		 * accept connections based on the "acceptCount" property.
		 */
		private int maxConnections = 8192;

		/**
		 * Maximum queue length for incoming connection requests when all possible request
		 * processing threads are in use.
		 */
		private int acceptCount = 100;

		/**
		 * Maximum number of idle processors that will be retained in the cache and reused
		 * with a subsequent request. When set to -1 the cache will be unlimited with a
		 * theoretical maximum size equal to the maximum number of connections.
		 */
		private int processorCache = 200;

		/**
		 * Comma-separated list of additional patterns that match jars to ignore for TLD
		 * scanning. The special '?' and '*' characters can be used in the pattern to
		 * match one and only one character and zero or more characters respectively.
		 */
		private List<String> additionalTldSkipPatterns = new ArrayList<>();

		/**
		 * Comma-separated list of additional unencoded characters that should be allowed
		 * in URI paths. Only "< > [ \ ] ^ ` { | }" are allowed.
		 */
		private List<Character> relaxedPathChars = new ArrayList<>();

		/**
		 * Comma-separated list of additional unencoded characters that should be allowed
		 * in URI query strings. Only "< > [ \ ] ^ ` { | }" are allowed.
		 */
		private List<Character> relaxedQueryChars = new ArrayList<>();

		/**
		 * Amount of time the connector will wait, after accepting a connection, for the
		 * request URI line to be presented.
		 */
		private Duration connectionTimeout;

		/**
		 * Static resource configuration.
		 */
		private final Resource resource = new Resource();

		/**
		 * Modeler MBean Registry configuration.
		 */
		private final Mbeanregistry mbeanregistry = new Mbeanregistry();

		/**
		 * Remote Ip Valve configuration.
		 */
		private final Remoteip remoteip = new Remoteip();

		//......
	}	

springboot的ServerProperties.Tomcat定义了connectionTimeout属性,用于指定接受连接之后等待uri的时间

customizeConnectionTimeout

org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizer.java

	private void customizeConnectionTimeout(ConfigurableTomcatWebServerFactory factory, Duration connectionTimeout) {
		factory.addConnectorCustomizers((connector) -> {
			ProtocolHandler handler = connector.getProtocolHandler();
			if (handler instanceof AbstractProtocol) {
				AbstractProtocol<?> protocol = (AbstractProtocol<?>) handler;
				protocol.setConnectionTimeout((int) connectionTimeout.toMillis());
			}
		});
	}

customizeConnectionTimeout将connectionTimeout写入到AbstractProtocol

AbstractProtocol

org/apache/coyote/AbstractProtocol.java

    public void setConnectionTimeout(int timeout) {
        endpoint.setConnectionTimeout(timeout);
    }

AbstractProtocol将timeout设置到endpoint

AbstractEndpoint

org/apache/tomcat/util/net/AbstractEndpoint.java

	public void setConnectionTimeout(int soTimeout) { 
		socketProperties.setSoTimeout(soTimeout); 
	}

    /**
     * Keepalive timeout, if not set the soTimeout is used.
     */
    private Integer keepAliveTimeout = null;
    public int getKeepAliveTimeout() {
        if (keepAliveTimeout == null) {
            return getConnectionTimeout();
        } else {
            return keepAliveTimeout.intValue();
        }
    }

AbstractEndpoint将timeout设置到socketProperties的soTimeout,另外它的getKeepAliveTimeout方法在keepAliveTimeout为null的时候,使用的是getConnectionTimeout

Http11Processor

org/apache/coyote/http11/Http11Processor.java

    public SocketState service(SocketWrapperBase<?> socketWrapper)
        throws IOException {
        RequestInfo rp = request.getRequestProcessor();
        rp.setStage(org.apache.coyote.Constants.STAGE_PARSE);

        // Setting up the I/O
        setSocketWrapper(socketWrapper);

        // Flags
        keepAlive = true;
        openSocket = false;
        readComplete = true;
        boolean keptAlive = false;
        SendfileState sendfileState = SendfileState.DONE;

        while (!getErrorState().isError() && keepAlive && !isAsync() && upgradeToken == null &&
                sendfileState == SendfileState.DONE && !protocol.isPaused()) {

            // Parsing the request header
            try {
                if (!inputBuffer.parseRequestLine(keptAlive, protocol.getConnectionTimeout(),
                        protocol.getKeepAliveTimeout())) {
                    if (inputBuffer.getParsingRequestLinePhase() == -1) {
                        return SocketState.UPGRADING;
                    } else if (handleIncompleteRequestLineRead()) {
                        break;
                    }
                }

                //......
            }
            
            //......
        }
        
        //......
    }          

Http11Processor的service方法在执行inputBuffer.parseRequestLine时传入了keptAlive、protocol.getConnectionTimeout()、protocol.getKeepAliveTimeout()参数

小结

springboot提供了tomcat的connection-timeout参数配置,其配置的是socket timeout,不过springboot没有提供对keepAliveTimeout的配置,它默认是null,读取的是connection timeout的配置。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当你在使用Tomcat时,如果出现“504 Gateway Timeout”错误提示,这通常意味着Tomcat在规定的时间内没有响应客户端请求。这可能是由于Tomcat服务器太忙而无法处理请求,或是网络连接出现问题,也可能是由于Tomcat配置不当引起的。 以下是一些可能的解决方案: 1. 增加Tomcat连接超时时间 可以尝试在Tomcat配置文件中增加连接超时时间,例如在server.xml文件中设置: ``` <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="600000" redirectPort="8443" /> ``` 这将将连接超时时间设置为10分钟(600000毫秒)。 2. 增加Tomcat线程池大小 如果Tomcat服务器繁忙并且无法处理请求,则可以尝试增加Tomcat线程池大小,以便能够处理更多的并发请求。在server.xml文件中,可以将Executor元素的maxThreads属性设置为更高的值,例如: ``` <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="400" minSpareThreads="20"/> ``` 这将将线程池的最大线程数设置为400。 3. 检查网络连接 如果Tomcat服务器与客户端之间的网络连接出现问题,则可以尝试检查网络连接是否正常。可以通过ping命令测试服务器是否可达,也可以尝试检查网络设备的日志,以查看是否有任何错误消息。 4. 检查Tomcat配置 最后,如果仍然无法解决问题,可以尝试检查Tomcat配置是否正确。例如,可以检查是否存在任何错误的配置项或无效的属性,以及是否存在任何冲突或重复的配置。可以查看Tomcat的日志文件以获取更多信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值