아키텍처와 함께

블로그 이미지
by gregorio
  • Total hit
  • Today hit
  • Yesterday hit

'분류 전체보기'에 해당되는 글 56건

  1. 2018.06.28
    Tomcat 설치 후 환경 설정
  2. 2018.06.28
    Linux에 Apache2.4 설치
  3. 2018.06.26
    Linux에서 VI editor theme 변경
  4. 2018.06.08
    Spring framewok Redis session 관리
  5. 2018.06.07
    JVM GC 설정

Tomcat이 설치된 후 환경설정을 통해 최적화를 수행하여야 한다.


Tomcat7을 기준으로 환경을 최적화 하는 방법이다.


1. .bash_profile 설정


# .bash_profile


# Get the aliases and functions

if [ -f ~/.bashrc ]; then

    . ~/.bashrc

fi


# User specific environment and startup programs

JAVA_HOME=/engn001/jdk1.7.0_80

TOMCAT_HOME=/engn001/tomcat-7.0.88

LOG_HOME=/logs001/

SRC_HOME=/sorc001/


PATH=$PATH:$HOME/.local/bin:$HOME/bin:$JAVA_HOME/bin


alias tomcat='cd $TOMCAT_HOME'

alias logs='cd $LOG_HOME/app'

alias src='cd $SRC_HOME'


alias applog='tail -f $LOG_HOME/app/dsc_app.log'


umask 022

export PATH JAVA_HOME


2. vi editor 설정


tomcat 계정 Home Directory에 .vimrc 파일 생성

colo evening

syntax on

set tabstop=4

set shiftwidth=4

set softtabstop=4

set expandtab



3. Tomcat catalina.sh 설정 변경


#################################################################

#  Set Java options start                                                                              #

#################################################################

DATE=`date +"%Y%m%d"`


CATALINA_OUT="/logs001/tomcat/catalina.out"


JAVA_OPTS=" $JAVA_OPTS -D$SERVER_NAME -server"

JAVA_OPTS=" $JAVA_OPTS -Xms1280m -Xmx1280m -XX:PermSize=256m -XX:MaxPermSize=256m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:SurvivorRatio=8 -XX:MaxDirectMemorySize=512m"

JAVA_OPTS=" $JAVA_OPTS -XX:+CMSClassUnloadingEnabled"

JAVA_OPTS=" $JAVA_OPTS -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/logs001/tomcat/dump/$SERVER_NAME-java_pid.hprof_$DATE"

#JAVA_OPTS=" ${JAVA_OPTS} -javaagent:${SCOUTER_AGENT_DIR}/scouter.agent.jar"

#JAVA_OPTS=" ${JAVA_OPTS} -Dscouter.config=${SCOUTER_AGENT_DIR}/conf/scouter.conf"

#JAVA_OPTS=" ${JAVA_OPTS} -Dobj_name=$SERVER_NAME"


if [ "$1" = "start" ]; then

    JAVA_OPTS=" $JAVA_OPTS -verbose:gc -Xloggc:/logs001/tomcat/gc/gc_$SERVER_NAME_$DATE.log"

    JAVA_OPTS=" $JAVA_OPTS -XX:+UseParallelGC -XX:ParallelGCThreads=8 -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintHeapAtGC -XX:+UseParallelOldGC -XX:-UseAdaptiveSizePolicy"

fi


#################################################################

#  Set Java options end                                                                                #

#################################################################

Garbage Collection은 Concurrent GC로 설정되어 있으며, 시스템에 따라 적절한 메모리, Log 등을 설정한다. 


4. server.xml 설정 변경


    <Connector port="8080" protocol="HTTP/1.1"

               maxPostSize="-1"

               maxParameterCount="100"

               connectionTimeout="20000"

               minSpareThreads="50"

               maxThreads="200"

               acceptCount="2000"

               redirectPort="8443" />

 Thread, Timeout 등 관련된 항목을 설정한다.

또한 AJP를 사용하는 경우에도 AJP Connector에 Thread, Timeout관련 설정을 수정한다.


  <Listener className="org.apache.catalina.security.SecurityListener" checkedOsUsers="root" />


root 계정으로 Tomcat을 시작할 수 없도록 Listener를 등록한다.



5. Start Script 작성


Tomcat 설치  디렉토리의 bin에 start.sh 스크립트 작성

[start.sh]


#!/bin/sh


# Licensed to the Apache Software Foundation (ASF) under one or more

# contributor license agreements.  See the NOTICE file distributed with

# this work for additional information regarding copyright ownership.

# The ASF licenses this file to You under the Apache License, Version 2.0

# (the "License"); you may not use this file except in compliance with

# the License.  You may obtain a copy of the License at

#

#     http://www.apache.org/licenses/LICENSE-2.0

#

# Unless required by applicable law or agreed to in writing, software

# distributed under the License is distributed on an "AS IS" BASIS,

# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

# See the License for the specific language governing permissions and

# limitations under the License.


# -----------------------------------------------------------------------------

# Start Script for the CATALINA Server

# -----------------------------------------------------------------------------


# resolve links - $0 may be a softlink

PRG="$0"


CATALINA_BASE=/engn001/tomcat-7.0.88

SERVER_NAME=xxxServer1


export CATALINA_BASE SERVER_NAME


while [ -h "$PRG" ] ; do

  ls=`ls -ld "$PRG"`

  link=`expr "$ls" : '.*-> \(.*\)$'`

  if expr "$link" : '/.*' > /dev/null; then

    PRG="$link"

  else

    PRG=`dirname "$PRG"`/"$link"

  fi

done


PRGDIR=`dirname "$PRG"`

EXECUTABLE=catalina.sh


exec "$PRGDIR"/"$EXECUTABLE" start "$@"



6. Stop Script 작성


Tomcat 설치  디렉토리의 bin에 stop.sh 스크립트 작성

[stop.sh]


#!/bin/sh


# Licensed to the Apache Software Foundation (ASF) under one or more

# contributor license agreements.  See the NOTICE file distributed with

# this work for additional information regarding copyright ownership.

# The ASF licenses this file to You under the Apache License, Version 2.0

# (the "License"); you may not use this file except in compliance with

# the License.  You may obtain a copy of the License at

#

#     http://www.apache.org/licenses/LICENSE-2.0

#

# Unless required by applicable law or agreed to in writing, software

# distributed under the License is distributed on an "AS IS" BASIS,

# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

# See the License for the specific language governing permissions and

# limitations under the License.


# -----------------------------------------------------------------------------

# Stop script for the CATALINA Server

# -----------------------------------------------------------------------------


# Better OS/400 detection: see Bugzilla 31132

os400=false


CATALINA_BASE=/engn001/tomcat-7.0.88

SERVER_NAME=xxxServer1


export CATALINA_BASE SERVER_NAME


PRG="$0"


while [ -h "$PRG" ] ; do

  ls=`ls -ld "$PRG"`

  link=`expr "$ls" : '.*-> \(.*\)$'`

  if expr "$link" : '/.*' > /dev/null; then

    PRG="$link"

  else

    PRG=`dirname "$PRG"`/"$link"

  fi

done


PRGDIR=`dirname "$PRG"`

EXECUTABLE=catalina.sh


exec "$PRGDIR"/"$EXECUTABLE" stop "$@"


AND

Linux에 Apache2.4를 설치하기 위해서는 다음 순서로 설치를 수행한다.


1. [apr install]


wget http://apache.mirror.cdnetworks.com/apr/apr-1.6.1.tar.gz


./configure --prefix=/usr/local/apr


cp -arp libtool libtoolT


make && make install



2. [apr-util install]


wget http://apache.mirror.cdnetworks.com/apr/apr-util-1.6.1.tar.gz


./configure --with-apr=/usr/local/apr --prefix=/usr/local/apr-util



xml/apr_xml.c:35:19: fatal error: expat.h: No such file or directory

 #include <expat.h>

                   ^

compilation terminated.

make[1]: *** [xml/apr_xml.lo] Error 1

make[1]: Leaving directory `/usr/local/apr-util-1.6.1'

make: *** [all-recursive] Error 1


yum install expat-devel


make && make install



3. [pcre 설치]


wget http://sourceforge.net/projects/pcre/files/pcre/8.31/pcre-8.31.tar.gz


./configure --prefix=/usr/local/pcre --disable-cpp 


make && make install



4. [openssl install]


wget http://www.openssl.org/source/openssl-1.0.2o.tar.gz


./config --prefix=/usr/local/openssl-1.0.2d --openssldir=/usr/local/openssl shared threads zlib


make & make install


echo /usr/local/openssl/lib >> /etc/ld.so.conf

/sbin/ldconfig


yum install openssl-devel




5. [apache install]


./configure --prefix=/home/ec2-user/apache --with-apr=/usr/local/apr --with-apr-util=/usr/local/apr-util --with-pcre=/usr/local/pcre --enable-so --enable-rewrite --with-mpm=worker --enable-mpms-shared=all --enable-ssl --with-ssl=/usr --enable-cache --enable-file-cache --enable-proxy --enable-proxy-connect --enable-proxy-http --enable-rewrite --enable-deflate


checking for zlib location... not found

checking whether to enable mod_deflate... configure: error: mod_deflate has been requested but can not be built due to prerequisite failures


yum을 이용하여 zlib 설치


yum -y install zlib-devel



configure: WARNING: OpenSSL version is too old

no

checking whether to enable mod_ssl... configure: error: mod_ssl has been requested but can not be built due to prerequisite failures


[open ssl install] 



AND

Linux 계정의 home directory에서


.vimrc 파일 생성한 후 다음과 같이 입력한다.


■.vimrc 파일 내용


colo evening

syntax on

set tabstop=4

set shiftwidth=4

set softtabstop=4

set expandtab



colo evening는 evening 테마를 적용한다는 의미임


VI Editor의 theme의 종류는


■VI Theme

blue.vim
darkblue.vim
default.vim
delek.vim
desert.vim
elflord.vim
evening.vim
koehler.vim
morning.vim
murphy.vim
pablo.vim
peachpuff.vim
ron.vim
shine.vim
slate.vim
torte.vim 

zellner.vim 


AND

Spring Framework에서 Session을 Redis에 저장하고 관리할 때 설정하는 방법이다.


서버 다중화 시 일반적을 Session Clustering을 다중화된 서버에 상호간 Session 정보를 동기화하기 위해 Multicast를 이용하는데 Amazon과 같은 Cloud를 사용할 경우 서버간 Multicast를 지원하지 않는다.


이 경우에 Session을 Redis에 관리하게 되는데, 본 글에서는 Spring Framework에 Redis를 이용하여 Session을 관리하는 설정 방법에 대한 설명이다.

그러나 Tomcat등 WAS가 Restart할 때 Session 정보는 Redis에 남아 있는게 되는데, 보안상에 이슈가 없을 경우 사용하면 좋을 듯 하다.


■ Configuration

 <?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util"

xmlns:cache="http://www.springframework.org/schema/cache"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd

http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd

        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd

        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<!-- This should not be removed -->

<context:annotation-config/>

<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>

<bean id="lettuceConnectionFactory" class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory" destroy-method="destroy">

<property name="hostName" value="xxxxx" />

<property name="port" value="6379" />

</bean>

<!-- Do not remove -->

<util:constant static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP"/>

<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">

<property name="connectionFactory" ref="lettuceConnectionFactory" />

</bean> 

</beans>



lettuceConectionFactory를 설정할 때 hostName과 Port를 설정하여 준다.


단순하게 Spring Framework에서 Redis를 이용하여 Session을 관리하는 방법을 설명하였다.


AND

Tomcat을 사용하는 경우 ../bin/setenv.sh에 다음과 같이 추가한다.


Garbage Collection 방식은 Parallel GC를 적용하고 있으며, New 영역에 256m를 할당하였다.


■Parallel GC 설정

#!/bin/sh


export JAVA_HOME=/engn001/jdk1.7.0_80

# Configuration Tomcat log file

CATALINA_OUT="/logs001/apache-tomcat-7.0.76/catalina.out"

#Configuration JVM Heap Size

JAVA_OPTS=" ${JAVA_OPTS} -Xms1280m -Xmx1280m -XX:MaxPermSize=256m -XX:NewSize=256m –XX:MaxNewSize=256m -XX:SurvivorRatio=16"

#Start Configuration GC

JAVA_OPTS=" ${JAVA_OPTS} -verbose:gc -XX:+DisableExplicitGC -Xloggc:/logs001/apache-tomcat-7.0.76/gc_`date +"%Y%m%d"`.log"

JAVA_OPTS=" ${JAVA_OPTS} -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintHeapAtGC"

#Apply Parallel GC

JAVA_OPTS=" ${JAVA_OPTS} -XX:+UseParallelGC  -XX:ParallelGCThreads=6 -XX:+UseParallelOldGC"

#End Configuration GC

JAVA_OPTS=" ${JAVA_OPTS} -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/logs001/heap/portal.hprof"

#Start Configuration SCOUT

JAVA_OPTS=" ${JAVA_OPTS} -javaagent:${SCOUTER_AGENT_DIR}/scouter.agent.jar"

JAVA_OPTS=" ${JAVA_OPTS} -Dscouter.config=${SCOUTER_AGENT_DIR}/conf/scouter.conf"

JAVA_OPTS=" ${JAVA_OPTS} -Dobj_name=SEHATI-PORTAL"

#End Configuration SCOUT



■ CMS GC 설정

# Base settings and GC logging

-server -XX:+AlwaysPreTouch  # First should be default, but we make it explicit, second pre-zeroes memory mapped pages on JVM startup -- improves runtime performance

# -Xloggc:gc-%t.log  # CUSTOMIZE LOCATION HERE - $path/gc-%t.log -- the %t in the gc log file path is so we get a new file with each JVM restart

-XX:NumberOfGCLogFiles=5 -XX:+UseGCLogFileRotation -XX:GCLogFileSize=20m # Limits the number of files, logs to folder 

-XX:+PrintGC -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:+PrintHeapAtGC -XX:+PrintGCCause

-XX:+PrintTenuringDistribution -XX:+PrintReferenceGC -XX:+PrintAdaptiveSizePolicy # gather info on object age & reference GC time for further tuning if needed.


# G1 specific settings -- probably should be default for multi-core systems with >2 GB of heap (below that, default is probably fine)

-XX:+UseG1GC

-XX:+UseStringDeduplication

-XX:+UnlockExperimentalVMOptions -XX:G1NewSizePercent=20  # Prevents G1 undersizing young gen, which otherwise causes a cascade of issues

-XX:+ParallelRefProcEnabled # parallelize reference processing, reducing young and old GC times. We use a LOT of weak references, so should have big impact.

-XX:+ExplicitGCInvokesConcurrent  # Avoid explicit System.gc() call triggering full GC, instead trigger G1

-XX:+UnlockDiagnosticVMOptions -XX:G1SummarizeRSetStatsPeriod=1 # Additional logging for G1 status

-XX:MaxMetaspaceExpansion=64M  # Avoids triggering full GC when we just allocate a bit more metaspace, and metaspace automatically gets cleaned anyway


# Tuned CMS GC - probably not worth using though (prefer G1 or default parallel GC if heap is <2 GB or so)

-XX:+UseConcMarkSweepGC

-XX:+ExplicitGCInvokesConcurrentAndUnloadsClasses # fixes issues with superlong explicit GC cycles (switches to concurrent GC, but also enables class unloading so we don't get memory leaks).

-XX:+CMSParallelRemarkEnabled -XX:+ParallelRefProcEnabled # parallelize re-marking and reference processing. The first will reduce full GC time, the latter should reduce both GC times -- we use a LOT of weak references, so should have big impact.

-XX:+CMSClassUnloadingEnabled # allows GC of classloaders & classes (important because we do some dynamic loading and because of groovy).

-XX:+ScavengeBeforeFullGC -XX:+CMSScavengeBeforeRemark # will force young gen GC before full GC (reduces full GC duration)

# Based on GC logs but may need refining, somewhere from 1:1 to 1:3 ratio is best because Jenkins makes mostly young garbage, cap at 3 G to limit minor GC pause duration

-XX:NewSize=512m -XX:MaxNewSize=3g -XX:NewRatio=2  


# Options NOT to use so far:

# * -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=<percent> - Generally suggested, but we don't have good benchmarks to collect these. So far we haven't done it


# Settings we *may* want to add for CMS but need more data for

#-Xms4g # because realistically allocating anything under 4 GB just increases startup time. We need that much RAM. Optional.

#-XX:NewSize=512m -XX:MaxNewSize=3g -XX:NewRatio=2 # start young gen somewhere reasonable and let it grow, but not too big (3 GB is a compromise b/w young GC pause time and the full GC pause time, the latter of which we know to be quite good even with a 10+ GB old gen heap)


# LOW-MEMORY use Jenkins, I.E. Jenkins on OpenShift, I have been using this for a long time to run Jenkins on an AWS t2.micro

# Will run A-OK with -Xmx384m if you limit load & workers

-XX:+UseSerialGC -XX:MinHeapFreeRatio=15 -XX:MaxHeapFreeRatio=30  -XX:MinMetaspaceFreeRatio=10 -XX:MaxMetaspaceFreeRatio=20 

# -XX:MaxMetaspaceSize=128m  -XX:CompressedClassSpaceSize=128m # Tweak to your needs.  This will run a decent-sized Jenkins however.  Too low == crashes

# Make sure to limit metaspace too, i.e. -XX:MaxMetaspaceSize=128m because it allocates a lot of RAM for that 


The over parameters are referred at https://gist.github.com/svanoort/66a766ea68781140b108f465be45ff00


'Java' 카테고리의 다른 글

Java Convert Map to XML 예제  (0) 2018.07.26
Java에서 Shell호출 방법  (0) 2018.07.05
Java Reflection 사용법  (0) 2018.04.12
JSP의 img, script에 jsessionid가 추가되는 경우  (0) 2018.02.22
Html a tag function call  (0) 2018.02.20
AND

ARTICLE CATEGORY

분류 전체보기 (56)
Spring Framrwork (33)
Linux (1)
APM (1)
Java (8)
python (0)
ant (1)
chart (1)
OS (1)
tomcat (1)
apache (1)
database (0)

RECENT ARTICLE

RECENT COMMENT

CALENDAR

«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

ARCHIVE

LINK