概要

  • 开启apr需要的环境
  • 环境搭建
  • 开启apr模式

    • spring boot
    • tomcat

      相关文件

  1. APR library
  2. OpenSSL libraries
  3. Java SE Development Kit (JDK)
  4. tomcat native

环境搭建

1.apr安装

解压apr包,默认安装目录在 /usr/local/apr 可以通过—prefix=xxx修改

  1. cd apr && sudo ./configure && sudo make && sudo make install

2.openssl安装

Mac系统

  1. brew install openssl

linux系统

In debian based Linux those dependencies could be installed by something like:

  1. apt-get install libapr1.0-dev libssl-dev

In rpm based Linux those dependencies could be installed by something like:

  1. yum install apr-devel openssl-devel

3.tomcat-native安装

下载tomcat-native 然后解压。

  1. cd /tomcat-native/native/ -\
  2. && sudo ./configure --with-apr=/usr/local/apr --with-ssl=/usr/local/opt/openssl -\
  3. --with-java-home=此处换成你本地的jdk地址指定到jdk目录#/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home -\
  4. && sudo make && sudo make install

编译成功后,会在/usr/local/apr/lib下有libtcnative-1.0.dylib的库文件,这个就是tomcat启动的依赖库

需要把该文件拷贝到jdk的Extensions目录下就行

  1. sudo cp /usr/local/apr/lib/libtcnative-1.dylib /Library/Java/Extensions/

开启apr模式

spring boot中开启apr模式

  1. @Bean
  2. public TomcatServletWebServerFactory tomcatServletWebServerFactory(){
  3. TomcatServletWebServerFactory serverFactory = new TomcatServletWebServerFactory();
  4. //设置协议为http1.1
  5. serverFactory.setProtocol(Constants.HTTP_11);
  6. Collection<LifecycleListener> listeners = serverFactory.getContextLifecycleListeners();
  7. listeners.forEach(lifecycleListener -> {
  8. if (lifecycleListener instanceof AprLifecycleListener) {
  9. AprLifecycleListener aprLifecycleListener = (AprLifecycleListener) lifecycleListener;
  10. //使用apr
  11. aprLifecycleListener.setUseAprConnector(true);
  12. }
  13. });
  14. return serverFactory;
  15. }

tomcat

  1. 修改protocol值
    Tomcat默认是HTTP/1.1,如果运行apr模式需要把protocol值修改成apr模式:org.apache.coyote.http11.Http11AprProtocol
  1. # vi server.xml
  2. <Connector port="8080" protocol="org.apache.coyote.http11.Http11AprProtocol"
  1. 修改SSLEngine
    1. # vi server.xml
    2. <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="off" />

启动

tomcat-apr模式 - 图1

如上图表示启动成功

压测

tomcat-apr模式 - 图2

总结

  • AprEndpoint:用C实现,通过JNI调用的。主要提升对静态资源(如HTML、图片、CSS、JS等)的访问性能。
  • AprEndpoint和NioEndpoint在性能上基本接近

结论:前后端分离的项目推荐使用Nio方式,不分离项目可以尝试开启apr模式

apr模式需要环境支持

tomca英文文档

http://tomcat.apache.org/native-doc/