如何更改Tomcat的JVM堆设置(- xms

来源:互联网 发布:淘宝网韩都衣舍商城 编辑:程序博客网 时间:2024/05/16 14:49

前言

Apache Tomcat是世界上广泛使用的Web容器。在生产环境中或在开发环境中运行应用程序时,配置所有正确的参数是非常重要的。现在我将介绍如何配置-Xmx、-Xmn 和-XX:PermSize 。

抛砖引玉

有时我们的线上程序会遇到内存溢出(OOM)的错误,可以通过更改tomcat的内存解决!以linux服务器、tomcat8.0.33 为例,网上很多在tomcat/bin/catalina.sh 中修改JAVA_OPTS=’…’,这种方法大错特错!当你进入到tomcat/bin/catalina.sh ,tomcat便告诫我们如果要修改内存分配,在setenv.sh文件中指定即可。第23行开始:

这里写图片描述


tomcat如何读取内存分配?


这是start.sh最后几行:

EXECUTABLE=catalina.sh# Check that target executable existsif $os400; then  # -x will Only work on the os400 if the files are:  # 1. owned by the user  # 2. owned by the PRIMARY group of the user  # this will not work if the user belongs in secondary groups  evalelse  if [ ! -x "$PRGDIR"/"$EXECUTABLE" ]; then    echo "Cannot find $PRGDIR/$EXECUTABLE"    echo "The file is absent or does not have execute permission"    echo "This file is needed to run this program"    exit 1  fifi


catalina.sh 140~147行

# but allow them to be specified in setenv.sh, in rare case when it is needed.CLASSPATH=if [ -r "$CATALINA_BASE/bin/setenv.sh" ]; then  . "$CATALINA_BASE/bin/setenv.sh"elif [ -r "$CATALINA_HOME/bin/setenv.sh" ]; then  . "$CATALINA_HOME/bin/setenv.sh"fi


可以看出:tomact启动时,start.sh 文件会去读取 catalina.sh, 如果 setenv.sh 文件不存在,则使用默认的配置,如果有,则按照setenv.sh分配内存。所以,我们只要在bin目录下新建一个setenv.sh,设置jvm内存分配规则就好。


那么,哪些参数是我们需要改动的呢?


  • -Xmx

    • 最大堆大小

    • 指定内存分配池的最大大小(以字节为单位)。这个值必须是1024大于2MB的倍数。添加字母k或k以表示千字节,或m或M表示兆字节。默认值是64MB。这个值的上限将在Solaris 7和Solaris 8 SPARC平台上大约4000M,在Solaris 2.6和x86平台上有2000M,减去开销。因此,简单地说,您是在说Java从可用内存中最多使用1024 MB。
      注意:- xmx和1024m之间没有空格

  • -Xmn

    • 年轻代大小
  • -XX:PermSize

    • 它用于为设置永久代大小。它是保存类文件的地方。

以我的服务器为例(4核8G ubuntu 16.04)

setenv.sh:

export CATALINA_OPTS="$CATALINA_OPTS -Xms2048m"export CATALINA_OPTS="$CATALINA_OPTS -Xmx2048m"export CATALINA_OPTS="$CATALINA_OPTS -XX:MaxPermSize=512m"


验证是否生效


这里不要用start.sh启动tomcat,用./catalina.sh run 启动,log 如下,挺详细的:

root@iZrj9efsj55mym7smowpe1Z:/opt/tomcat8/bin# ./catalina.sh run...06-Sep-2017 14:31:35.207 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Xms2048m06-Sep-2017 14:31:35.208 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Xmx2048m06-Sep-2017 14:31:35.208 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -XX:MaxPermSize=512m...06-Sep-2017 14:31:35.911 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 582 ms


如果是win环境,在tomcat/bin/下添加setenv.bat 即可!

原创粉丝点击