1. springboot2对embeded container的配置
@Component
public class EmbeddedTomcatConfig implements
WebServerFactoryCustomizer {
@Override
public void
customize(ConfigurableServletWebServerFactory factory) {
((TomcatServletWebServerFactory)factory).addConnectorCustomizers(new
TomcatConnectorCustomizer() {
@Override
public void customize(Connector connector) {
Http11NioProtocol protocol = (Http11NioProtocol)
connector.getProtocolHandler();
protocol.setMaxConnections(200);
protocol.setMaxThreads(200);
protocol.setSelectorTimeout(3000);
protocol.setSessionTimeout(3000);
protocol.setConnectionTimeout(3000);
}
});
}
}
springboot2.x的相关类如下:
org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory
org.springframework.boot.web.server.WebServerFactoryCustomizer
org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer
org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory
2. tomcat 8.0以后对请求URL做了严格的过滤
就是严格按照 RFC 3986规范进行访问解析,而 RFC
3986规范定义了Url中只允许包含英文字母(a-zA-Z)、数字(0-9)、-_.~4个特殊字符以及所有保留字符(RFC3986中指定了以下字符为保留字符:!
* ’ ( ) ; : @ & = + $ , / ? # [ ])。
这可能会遇到一个问题,比如参数中传了一段json,而"{"不在RFC3986中的保留字段中,就会认为是非法的。这时候你的请求压根到不了你的方法就被tomcat拦截了。直接报:java.lang.IllegalArgumentException:
Invalid character found in the request target. The valid characters
are defined in RFC 7230 and RFC 3986
3.解决方法:
import org.apache.catalina.connector.Connector;
import
org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import
org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import
org.springframework.boot.web.server.WebServerFactoryCustomizer;
import
org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;
@Component
public class PortalTomcatWebServerCustomizer implements
WebServerFactoryCustomizer {
@Override
public void
customize(ConfigurableServletWebServerFactory container) {
TomcatServletWebServerFactory containerFactory =
(TomcatServletWebServerFactory) container;
containerFactory.addConnectorCustomizers(new
TomcatConnectorCustomizer() {
@Override
public void customize(Connector connector) {
connector.setAttribute("relaxedQueryChars",
"[]|{}^"<>");//这里需要转义,微博上被转换了
connector.setAttribute("relaxedPathChars", "[]|");
}
});
}
}