캠핑과 개발

Quartz 문서

DEVELOPMENT/Java2011. 7. 13. 21:02


 Object something = new Integer(123);
 String theType = "java.lang.Number";
 Class<? extends Number> theClass = Class.forName(theType).asSubclass(Number.class);
 Number obj = theClass.cast(something);

'DEVELOPMENT > Java' 카테고리의 다른 글

Apache Daemon 사용하기  (0) 2012.05.17
Quartz 문서  (0) 2011.07.13
log4jdbc를 활용하여 쿼리 로그 남기기  (0) 2011.06.01
Commons-lang, Commons-io 사용 샘플  (0) 2011.06.01
JAVA Tip  (0) 2011.04.13


1. 필요한 라이브러리 다운 로드
 - log4jdbc3-1.1.jar(If you are using JDK 1.4 or 1.5, you should use the JDBC 3 version of log4jdbc.)
 - slf4j-api-1.5.0.jar(log4jdbc와 logging 서비스 연동을 위한 API 제공)
 - slf4j-log4j12-1.5.2.jar(log4jdbc와 Log4j 기반의 Logging 서비스 연동을 위한 구현 라이브러리 제공)

2. DataSource 서비스 속성 정의 파일 정의

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName"
value="net.sf.log4jdbc.DriverSpy"/>
<property name="url"
value="jdbc:log4jdbc:mysql://localhost:3306/member?useUnicode=true
&characterEncoding=utf8"/>
<property name="username" value="member"/>
<property name="password" value="member"/>
<property name="maxActive" value="30"/>
<property name="maxIdle" value="3"/>
<property name="maxWait" value="-1"/>
</bean>

3. Logger 정의

 - jdbc.sqlonly : SQL문만을 로그로 남기며, PreparedStatement일 경우 관련된 argument 값으로 대체된 SQL문이 보여진다.
 - jdbc.sqltiming : SQL문과 해당 SQL을 실행시키는데 수행된 시간 정보(milliseconds)를 포함한다.
 - jdbc.audit : ResultSet을 제외한 모든 JDBC 호출 정보를 로그로 남긴다. 많은 양의 로그가 생성되므로 특별히 JDBC 문제를 추적해야 할 필요가 있는 경우를 제외하고는 사용을 권장하지 않는다.
 - jdbc.resultset : ResultSet을 포함한 모든 JDBC 호출 정보를 로그로 남기므로 매우 방대한 양의 로그가 생성된다.
 - 예) log4j.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration
xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %5p [%c] %m%n" />
</layout>
</appender>

<appender name="rollingFile"
class="org.apache.log4j.RollingFileAppender">
<param name="File" value="C:\\logs\\error\\error.log"/>
<param name="Append" value="true"/>
<param name="MaxFileSize" value="100MB"/>
<param name="MaxBackupIndex" value="2"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %p [%c]-%m%n" />
</layout>
</appender>

<logger name="org.springframework.jdbc">
<level value="DEBUG"/>
<appender-ref ref="console"/>
</logger>

<logger name="com.mimul">
<level value="DEBUG"/>
<appender-ref ref="console"/>
<appender-ref ref="rollingFile"/>
</logger>

<logger name="org.apache.struts">
<level value="DEBUG"/>
<appender-ref ref="console"/>
<appender-ref ref="rollingFile"/>
</logger>

<!-- log SQL (pre-execution) plus exceptions caused by SQL -->
<logger name="jdbc.sqlonly" additivity="false">
<level value="DEBUG" />
<appender-ref ref="console" />
<appender-ref ref="rollingFile"/>
</logger>

<!-- log SQL with timing information, post execution -->
<logger name="jdbc.sqltiming" additivity="false">
<level value="DEBUG" />
<appender-ref ref="console" />
<appender-ref ref="rollingFile"/>
</logger>

<!-- only use the two logs below to trace ALL JDBC information,
NOTE: This can be very voluminous! -->
<!-- log all jdbc calls except ResultSet calls -->
<logger name="jdbc.audit" additivity="false">
<level value="DEBUG" />
<appender-ref ref="console" />
<appender-ref ref="rollingFile"/>
</logger>

<!-- log the jdbc ResultSet calls -->
<logger name="jdbc.resultset" additivity="false">
<level value="DEBUG" />
<appender-ref ref="console" />
<appender-ref ref="rollingFile"/>
</logger>

<!-- this log is for internal debugging of log4jdbc, itself -->
<!-- debug logging for log4jdbc itself -->
<logger name="log4jdbc.debug" additivity="false">
<level value="DEBUG" />
<appender-ref ref="console" />
<appender-ref ref="rollingFile"/>
</logger>
<root>
<level value="DEBUG" />
<appender-ref ref="console" />
<appender-ref ref="rollingFile"/>
</root>
</log4j:configuration>


4. 로그 처리 결과 
 
2008-10-24 10:23:02 [jdbc.audit] - <2. Connection.setAutoCommit(true)
2008-10-24 10:23:02 [java.sql.Connection] - <{conn-100003} Connection>
2008-10-24 10:23:02 [java.sql.Connection] - <{conn-100003}
Preparing Statement:
select count(userid) as total from MEMBER where userid = ?
and password = ? >
2008-10-24 10:23:02 [jdbc.audit] -
<2. Connection.prepareStatement(
select count(userid) as total from MEMBER where
userid = ? and password = ? )
2008-10-24 10:23:02 [jdbc.audit] -
<2. PreparedStatement.setQueryTimeout(0)
2008-10-24 10:23:02 [jdbc.audit] -
<2. PreparedStatement.setString(1, "pepsi")
2008-10-24 10:23:02 [jdbc.audit] -
<2. PreparedStatement.setString(2, "1234")
2008-10-24 10:23:02 [java.sql.PreparedStatement] -
<{pstm-100004}
Executing Statement:
select count(userid) as total from MEMBER where userid = ? and password = ? >
2008-10-24 10:23:02 [java.sql.PreparedStatement]
- <{pstm-100004}
Parameters: [pepsi, 1234]>
2008-10-24 10:23:02,281 DEBUG [java.sql.PreparedStatement] -
<{pstm-100004} Types: [java.lang.String, java.lang.String]>
2008-10-24 10:23:02,281 DEBUG [jdbc.sqlonly] -
<2. select count(userid) as total from MEMBER where userid = 'pepsi'
and password = '1234' >
2008-10-24 10:23:02,281 DEBUG [jdbc.sqltiming] -
<2. select count(userid) as total from MEMBER where userid = 'pepsi'
and password = '1234'
{executed in 0 msec}>
2008-10-24 10:23:02 [jdbc.audit] - <2. PreparedStatement.execute()
2008-10-24 10:23:02 [jdbc.audit] - <2. PreparedStatement.getResultSet()
2008-10-24 10:23:02 [java.sql.ResultSet] - <{rset-100005} ResultSet>
2008-10-24 10:23:02 [jdbc.resultset] - <2. ResultSet.getType()
2008-10-24 10:23:02 [jdbc.resultset] - <2. ResultSet.next() returned true
2008-10-24 10:23:02 [jdbc.resultset] - <2. ResultSet.getMetaData() returned
2008-10-24 10:23:02 [jdbc.resultset] - <2. ResultSet.getInt(TOTAL) returned 1
2008-10-24 10:23:02 [jdbc.resultset] - <2. ResultSet.wasNull() returned false
2008-10-24 10:23:02 [jdbc.resultset] - <2. ResultSet.next() returned false
2008-10-24 10:23:02, [java.sql.ResultSet] - <{rset-100005} Header: [TOTAL]>
2008-10-24 10:23:02 [java.sql.ResultSet] - <{rset-100005} Result: [1]>
2008-10-24 10:23:02 [jdbc.audit] - <2. Connection.getMetaData()
2008-10-24 10:23:02 [jdbc.resultset] - <2. ResultSet.close()
2008-10-24 10:23:02 [jdbc.audit] - <2. PreparedStatement.close()
2008-10-24 10:23:02 [jdbc.audit] - <2. Connection.isClosed()
2008-10-24 10:23:02 [jdbc.audit] - <2. Connection.getAutoCommit()
2008-10-24 10:23:02 [jdbc.audit] - <2. Connection.clearWarnings()
2008-10-24 10:23:02 [jdbc.audit] - <2. Connection.setAutoCommit(true)

jdbc.sqltiming 로그에 보면 실행된 FULL Query가 보일 것입니다.
 
[출처] : http://mimul.com/pebble/default/2008/10.html

'DEVELOPMENT > Java' 카테고리의 다른 글

Quartz 문서  (0) 2011.07.13
[JAVA] 동적 캐스팅  (0) 2011.06.10
Commons-lang, Commons-io 사용 샘플  (0) 2011.06.01
JAVA Tip  (0) 2011.04.13
JNI 라이브러리 파일의 경로 동적 설정  (0) 2011.02.25

package client;

import java.io.File;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

public class CommonClient
{
public static void main(String[] args)
{
String dir = "D:\\temp";
File dirFile = new File(dir);
String[] extensions = {"txt", "html"};

try {
// StringUtils
System.out.println("StringUtils.isEmpty : " +
(StringUtils.isEmpty(null) && StringUtils.isEmpty("")));
System.out.println("StringUtils.isBlank : " +
StringUtils.isBlank(" \n\t"));
System.out.println("StringUtils.substringAfterLast : " +
StringUtils.substringAfterLast("일.이.삼.사", "."));
System.out.println("StringUtils.substringBeforeLast : " +
StringUtils.substringBeforeLast("일.이.삼.사", "."));
String[] splitArr = StringUtils.split("일.이.삼.사", '.');
for (int i = 0, n = splitArr.length; i < n; i++ ) {
System.out.println("split : " + splitArr[i]);
}
System.out.println("StringUtils.leftPad : " +
StringUtils.leftPad("1", 5, '0'));
// FileUtils
// 문자열을 해당 파일에 카피
File file1 = new File(dir, "file1.txt");
String filename = file1.getAbsolutePath();
FileUtils.writeStringToFile(file1,
filename, "UTF-8");

// 파일을 읽어 문자열로 출력
String file1contents = FileUtils.readFileToString(file1, "UTF-8");
System.out.println("file1contents : " + file1contents);
System.out.println("list dir : " +
FileUtils.listFiles(dirFile, extensions, false));

// 해당 문자열을 파일에 저장
File file2 = new File(dir, "file2.txt");
String filename2 = file2.getAbsolutePath();
FileUtils.writeStringToFile(file2, filename2,
"UTF-8");
String file2contents =
FileUtils.readFileToString(file2, "UTF-8");
System.out.println("file2contents : " + file2contents);

// 디렉토리 강제 할당
File testFile = new File(dir, "subdir");
FileUtils.forceMkdir(testFile);
System.out.println("list dir : " +
FileUtils.listFiles(testFile,
extensions, false));

// 파일 카피
File testFile2 = new File(dir, "testFile1Copy.txt");
File testFile1 = new File(dir, "testFile1.txt");
FileUtils.copyFile(testFile1, testFile2);
//IOUtils.copy(inputStream, outputStream); 와 같음
FileUtils.forceDelete(testFile2);
System.out.println("list dir : " +
FileUtils.listFiles(dirFile, extensions, false));

File directory = new File(dir, "subdir");
FileUtils.copyFileToDirectory(testFile1, directory);

// 파일 읽어서 문자열로 리턴
String readFile = FileUtils.readFileToString(file1, "UTF-8");
//String readFile = IOUtils.toString(inputStream);
System.out.println("readFile : " + readFile);

// 라인 별로 파일 내용 읽기
List<String> readList = FileUtils.readLines(file1, "UTF-8");
//List<String> readList = IOUtils.readLines(inputStream);
for (int j = 0, sl = readList.size(); j < sl ; j++) {
System.out.println("readList : " + readList.get(j));
}

long size = FileUtils.sizeOfDirectory(dirFile);
System.out.println(size + " bytes");
System.out.println(FileUtils.byteCountToDisplaySize(size));

} catch (Throwable e) {
e.printStackTrace();
}
}
}


출처 : http://mimul.com/pebble/default/2008/10.html

'DEVELOPMENT > Java' 카테고리의 다른 글

[JAVA] 동적 캐스팅  (0) 2011.06.10
log4jdbc를 활용하여 쿼리 로그 남기기  (0) 2011.06.01
JAVA Tip  (0) 2011.04.13
JNI 라이브러리 파일의 경로 동적 설정  (0) 2011.02.25
Velocity의 기본 문법  (0) 2011.02.11

JAVA Tip

DEVELOPMENT/Java2011. 4. 13. 10:34

1. 띄워쓰기 공백 제거

문자열.replaceAll(\\p{Space}, "");

참고 : http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html


JNI를 사용하여 c 함수를 호출할 때의 실제 라이브러리 파일을 로딩하기 위하여 다음과 같이한다.

  1. 환경 변수 PATH에 포함된 디렉토리에 dll 파일을 카피해 둔다.
  2. java 실행 시 -Djava.library.path=c:\library\path 와 같이 dll 파일이 있는 디렉토리를 설정한다.

그런데 위 방법들이 마땅치 않을 수 있다. 웹 어플리케이션의 경우 필요한 파일 모두를 해당 웹 어플리케이션 디렉토리 밑에 모두 모아두고 싶은 경우이다. 만약 1번의 방법을 사용한다면 해당 dll만 웹하고는 전혀 관계없는 C:\windows 같은 시스템 폴더에 두어야 한다. 혹은 dll이 있는 디렉토리 이름을 환경변수 PATH에 포함시켜야 한다. 역시 깔끔하지 않다. 2번 째 방법을 적용하려면 WAS의 실행 스크립트를 수정하여야 한다. 특정 웹 어플리케이션을 설치하기 위하여 WAS 자체를 건드리는 것은 바람직하지 않다.

실행 시에 System 속성 "java.library.path"를 설정하고, 그 변경된 것이 적용되면 좋겠는데, 실행전에 설정하지 않으면 적용되지 않는다.

java.lang.ClassLoader의 코드를 보면 "java.library.path"에 설정된 값을 초기에 한번 String[] usr_paths에 담아두고 그것을 계속 사용한다. reflection을 사용하여 usr_paths에 원하는 경로를 추가하게 하면 되겠다. 하지만 이런 방법은 바람직하진 않고, 또 어떤 위험성이 있는지도 추측하기 힘든 꼼수다.

아래 코드를 달긴 하지만, 어떤 위험성이 있는지는 아직 파악되지 않았다.
그리고 ClassLoader의 private 속성 usr_paths의 이름이 각 JVM마다 다 똑같다는 것도 확인 안되었고.
무엇 보다도 치명적인 것은 private으로 은닉화시켜 놓은 것은 언제든지 변경될 수 있고, 유지보수가 어렵다는 것이다.
꼼수다운 단점이다.

 public static void loadLibrary(String libraryPath, String libraryName) throws LibraryLoadingException {
     
  // 라이브러리 패스를 추가
     addLibrarayPath(libraryPath);
  // 라이브러리를 로딩    
     System.loadLibrary(libraryName);
     
    }

 private static void addLibrarayPath(String libraryPath) throws LibraryLoadingException {
  
  if(libraryPath==null) { return; }
  if(libraryPath.equals("")) { return; }
  
     Field usrPathsField;
  // ClassLoader의 String[] usr_paths 필드를 구하고
  // usr_paths의 값은 시스템 속성 java.library.path의 값으로 초기에 한번만 설정된다.
  try {
   usrPathsField = getField(ClassLoader.class, "usr_paths");
  } catch (ReflectionFailException e) {
   throw new LibraryLoadingException("library loading failed.", e);
  }

  if(usrPathsField==null) {
   throw new LibraryLoadingException("library loading failed. invalid attribute usr_paths");
  }

  // private으로 선언된 것을 접근 가능하게 바꿔주고.
     usrPathsField.setAccessible(true);
     
     String[] userPaths;
  try {
   // 실제 설정된 값을 구하고
   userPaths = (String[])usrPathsField.get(null);
  } catch (IllegalArgumentException e) {
   throw new LibraryLoadingException("library loading failed.", e);
  } catch (IllegalAccessException e) {
   throw new LibraryLoadingException("library loading failed.", e);
  }
     
  // 만약 추가할 패스가 이미 있다면 더 할일이 없다. 나간다.
     for(int i=0; i<userPaths.length; i++) {
      if(libraryPath.equalsIgnoreCase(userPaths[i])) {
       return;
      }
     }

  // 새로운 패스를 추가하고     
     String[] newUserPaths = new String[userPaths.length+1];
     for(int i=0; i<userPaths.length; i++) {
      newUserPaths[i] = userPaths[i];
     }
     newUserPaths[newUserPaths.length-1] = libraryPath;
     
  // 추가된 패스가 포함된 새로운 값을 설정한다.
     try {
   usrPathsField.set(null, newUserPaths);
  } catch (IllegalArgumentException e) {
   throw new LibraryLoadingException("library loading failed.", e);
  } catch (IllegalAccessException e) {
   throw new LibraryLoadingException("library loading failed.", e);
  }
     
 }


 public static Field getField(Class clazz, String fieldName) throws ReflectionFailException {
  
  if(clazz==null) { return null; }
  if(fieldName==null) { return null; }
  
  Field field = null;
  
  Exception rootException = null;
  try {
   field = clazz.getDeclaredField(fieldName);
   return field;
  } catch (SecurityException e) {
   rootException = e;
  } catch (NoSuchFieldException e) {
   rootException = e;
  }
  
  Class superClass = clazz.getSuperclass();
  while(superClass!=null) {
   try {
    field = superClass.getDeclaredField(fieldName);
    return field;
   } catch (SecurityException e) {
   } catch (NoSuchFieldException e) {
   }
   superClass = superClass.getSuperclass();
  }
  
  throw new ReflectionFailException("getting field "+fieldName+" failed.", rootException);
 }

 


2009/05/11 추가사항

이외에 다른 방법이 있다. System.loadLibrary()는 시스템 속성 "java.library.path"의 값을 사용하기 전에 메소드를 호출한 클래스의 클래스로더의 findLibrary(String libraryName)을 호출한다. 해당 라이브러리의 경로를 반환하는 메소드 이다. 만약 요 메소드의 반환값을 적절히 해주면 해결될 것이다. 가장 합벅적인(?)인 방법이다. 그러나 클래스 로드를 따로 개발해야 한다는 부담이 있다. 더군다나 native 라이브러리를 호출하는 코드를 건드리지 못한다면(다른 곳에서 가져온 라이브러리일 경우) 요 방법은 적용하지 못한다. 실제로 테스트해본 결과 로딩은 되긴 한다. 그러나 라이브러리간의 의존성에서 실패한다. a.dll이 있고 b.dll이 있고, a.dll이 b.dll을 사용하는 경우이다. java 코드에서는 a.dll을 잘 로딩했는데 a.dll이 b.dll을 로딩하지 못하였다. "Can't find dependent libraries" 메시지의 java.lang.UnsatisfiedLinkError가 발생한다. 이러한 것이 내가 작성한 코드의 버그인지 다른 원인인지도 모르는 상태에서 덮어 버렸다.

혹시나 해서 비슷한 코드를 찾아 보았다. theyard라는 프로젝트에 JNILibraryLoader라는 클래스가 있다.(http://code.google.com/p/theyard/source/detail?r=168). 가져다 사용해 보니 훌륭하게 동작한다. 내부를 들여다 보니 System.load(String fileName)을 사용하고 있다. 요메소드가 System.loadLibrary()와 무슨 차이가 있는지는 파악하진 않았다. System.load()가 실패하면 loadLibrary()를 호출한다. 그리고 더 마음에 드는 것은 OS별 라이브러리 파일의 확장자를 알아서 처리해 주고, 라이브러리의 버전까지도 명시할 수 있다. 실제 수정한 코드를 첨부한다. JniLibraryLoader.java 사용방법은 다음과 같다.
JniLibraryLoadder.load("c:/some/path", "myLib");


System.loadLibrary()메소드가 시스템 속성 "java.library.path"의 값을 그때 마다 읽지 않고 한번만 읽고는 그 값을 사용하게 한 것은 무언가 이유가 있을 것 같다. 뭔지는 잘 모르겠는데, 이렇게 처리하는 것이 그 무언지 모르는 위험성을 안고 가는것 같아 찜찜하다.

[출처] http://aploit.egloos.com/4937154

'DEVELOPMENT > Java' 카테고리의 다른 글

Commons-lang, Commons-io 사용 샘플  (0) 2011.06.01
JAVA Tip  (0) 2011.04.13
Velocity의 기본 문법  (0) 2011.02.11
Spring - Quartz를 사용하여 스케쥴러 구현하기  (0) 2011.02.08
EHCache를 이용한 캐시 구현  (0) 2011.01.05

1. VTL(Velocity Template Language) 장점
@ UI 디자이너와 개발자의 병렬 개발 가능
@ 각각의 영역에 집중가능
@ 유지보수 용의
@ JSP,PHP 대체방안 제시


2. VTL 문장은 # 으로 시작하며  변수명은 $ 로 표시한다.
- VTL 문장의 시작은 #으로 시작합니다.
- 변수의 시작은 $로 시작합니다.

# set( $foo = "Velocity")


따라서 다음과 같이 #set($color = "blue") 라고 하면 $color 변수에 String "blue" 값을 담는 VTL 문법이 되겠습니다. 그러면 Hello World 를 출력해보도록 하겠습니다.

<html>
<body>
#set($color = "blue")
내가 좋아하는 색깔은 $color 입니다.
</body>
</html>


*VTL을 실행하기 위해서는 필수적인 Jar 파일이 있습니다. 아래의 Jar 파일을 WEB-INF/lib 안에 복사하세요

velocity-dep-*.jar : velocity 그리고 관련된 클래스 파일
velocity-tools-*.jar : velocity tool
commons-digester
commons-collections
commons-beanutils


3. 주석처리방법
한줄 : ##
여러줄 : #*  *#


VTL에서 주석은 다음과 같이 사용합니다. 일반적으로 주석이라 하면 <!-- --> 을 사용했는데, VTL은 다음과 같은 주석을 사용합니다.

## This is Commnets!!

#*
This is Comments!!
*#



4. 자바객체사용해서 하위 객체 접근이 가능하다
$ custom.Address
$ custom.getAddress()



5. 값을 불러오는 여러가지 방법
$ customer.address 를 다음과 같이 표현할수 있다.
$ getaddress()
$ getAddress()
$ get("address")
$ isAddress()


6. 중간에 변수가 들어가서 잘못 파싱되는것을 방지하기위해 쓰는 방식인데 기본적으로 이렇게 처리하는 버릇을 들이자 
Jack is a $vicemaniac.
Jack is a ${vice}maniac.


7. 값이 없을 시에 공백처리를 원할때
<input type="text" name="email" value="$!email>
좀더 안전하기를 원하면 value="$!{email}"


8. #set 지시자 사용시 큰따옴포("") 안의 내용은 파싱되어 그 결과물을 출력한다.
#set( $template = "$directoryRoot / $templateName")
지시 및 연산 변수의 경우는 다음과 같습니다.

#set( $a= 10 )
#set( $b= 20 )
#set( $value = $a + 1 ) ## 11
#set( $value = $b - 1 ) ## 9
#set( $value = $a * $b ) ## 200
#set( $value = $a / $b ) ## 0.5


9. '' 작은 따옴표는 파싱되지 않고 내용이 그대로 출력되지만

velocity.properties 안의 Stringliterals.interpolote = false 값을 바꿈으로서 파싱이 되도록 설정한다.

10. for 문으로 반복문을 처리하고 싶을때
iterator 와 비슷한 형태의 구조이다.
#foreach($page in $boardList)
<!-- 처리하고자 하는 내용 -->
#end



11. if 문을 쓰고싶을때
#if($velocityCount <= 3)
   $item
#end

그 외 제어문은 다음과 같습니다.

#set($a = 10)

#if($a > 9)
   9보다 큽니다
#elseif($a == 10)
   10과 같습니다
#end


반복문의 경우는 다음과 같습니다.

<ul>
#foreach( $product in $allProducts )
<li>$product.id , $product.name</li>
#end
</ul>


일반적인 foreach와 같습니다. Controller에서 ArrayList 객체를 allProducts로 네임을 정해서 View 단으로 보냈다면 위와 같은 문법으로 allProducts의 객체를 $product로 담고, $product를 통해 각 프로퍼티를 출력할 수 있습니다.

출처 : http://dsstory.tistory.com/105


가끔 서버에서 주기적으로 어떠한 작업을 하고자 할때 리눅스에서는 크론탭을 사용하여 주기적으로 어떠한 작업을 처리합니다.
이런 주기적 작업을 처리하기위해 Spring에서 지원해 주는 Quartz스케쥴러를 통해 크론탭과 같은 역할을 하는 스케쥴러를 작성할 수 있습니다.
이번에는 Spring 과 Quartz를 연동하여 스케줄러를 작성해 보겠습니다.

작업순서는
스프링 기본 세팅 -> Quartz 세팅 순으로 작업하겠습니다.

1. 스프링 기본 설정
1) springframework.org 로 이동하셔서 스프링 라이브러리를 다운 받습니다.

위와 같은 페이지가 뜨면 해당사항을 입력하시고 Access Download 를 클릭하셔서 다운로드 페이지로 이동합니다. (귀찮으신 분들은 하단의 파란색으로 "download page"를 선택하시면 입력하시지 않고도 다운로드 페이지로 이동하실수 있습니다.

많은 버전의 라이브러리 중 spring-framework-2.5.6.SEC02.zip 를 다운 받습니다. 다른 버전을 다운 받으셔도 상관없습니다만 버전에 따라 세팅 내용이 조금 씩 달라지므로 같은 버전의 라이브러리로 진행하는 것이 나을 것같네요~^^.

2) 이렇게 라이브러리까지 다운로드 받고 나면 Eclipse와 같은 IDE에서 Dynamic Web Project를 선택하여 Project를 한개 생성합니다.
(저는 SpringQuartz 라는 이름으로 생성했습니다.)

3) 프로젝트가 생성되면 프로젝트 안에 /WEB-INF/lib 디렉토리에 스프링 라이브러리를 압축 푼 곳에 있는 dist/spring.jar 파일을 추가합니다.
* 팁 : 프로젝트를 진행하다 보면 위와같이 라이브러리 버전이 없는 jar파일을 그냥 추가하는 경우가 있는데 나중에 라이브러리를 업데이트 해야 할일이 생기게 되면 위와같이 spring.jar 라고 되어있으면 지금 적용되어 있는 버전이 몇 인지 알수가 없습니다. 그렇기 때문에 항상 라이브러리 추가하실때는 추가하시는 라이브러리의 버전 번호를 파일이름 뒤에 추가하는 습관을 들이 시는게 좋습니다.
     ex) spring-2.5.6.jar

4) 프로젝트 안에 생성된 web.xml에 Spring을 사용하기 위한 세팅을 추가해 줍니다.
* 저는 Quartz를 사용하기 위한 최소한의 Spring 세팅을 해놓았기 때문에 세팅 내용이 단순합니다. 만약 웹프로젝트와 함께 Quartz를 사용하신다면 웹에 맞게 설정하시고 사용하셔야 함을 알려드립니다.^^
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee"      
  4.     xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee      
  5.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  id="WebApp_ID" version="2.5">    <listener>  
  6.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>     
  7.     </listener>      
  8.     <context-param>          
  9.         <param-name>contextConfigLocation</param-name>         
  10.         <param-value>/WEB-INF/config/applicationContext*.xml</param-value>  
  11.     </context-param>  
  12. </web-app>  


5) 쿼츠 라이브러리를 다운로드 받고 라이브러리를 추가해 줍니다.
쿼츠 라이브러리 다운로드 하신다음 압축을 풀어 줍니다.
해당 라이브러리를 프로젝트의 lib 디렉토리에 복사하여 넣어줍니다.
- quartz-all-1.8.3.jar
- 압축푼 lib 디렉터리의 log4j-1.2.14.jar
- 압축푼 lib 디렉터리의 slf4j-api-1.5.10.jar
- 압축푼 lib 디렉터리의 slf4j-log4j12-1.5.10.jar
를 추가 해 줍니다.
마지막으로 apache의 commons-logging-1.1.1.jar 를 다운로드 하셔서 위와 같이 프로젝트의 lib에 추가해주시면 라이브러리 추가는 끝이 납니다.

6) Quartz의 핵심적인 기능을 할 /WEB-INF/config/applicationConext.xml 을 작성합니다.
스케쥴러의 핵심 세팅은 3가지 정도 입니다.
하나. 실제 주기적으로 실행될 클래스 등록
둘. 스케줄러가 동작하는 interval time 설정
셋. 실제 동작하게 끔 설정

이런 세가지가 있겠습니다.

스케줄러 동작방식에는 두가지가 존재 합니다.
-Simple : interval time이 간단하게 동작하는 방식으로 몇초, 혹은 몇분, 몇시간 단위로 작동하고 싶을때 사용합니다.
<Simple type setting>
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:context="http://www.springframework.org/schema/context"  
  4.        xmlns:p="http://www.springframework.org/schema/p"  
  5.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  6.        xsi:schemaLocation="http://www.springframework.org/schema/beans      
  7.                            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd   
  8.                            http://www.springframework.org/schema/context   
  9.                            http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
  10.     <!-- 하나.주기적으로 실행될 클래스 설정 -->  
  11.     <!-- property name은 jobClass로 fix, value는 사용자가 작성한 class 파일 위치 -->  
  12.     <bean id="simpleQuartzJob" class="org.springframework.scheduling.quartz.JobDetailBean">  
  13.         <property name="jobClass" value="net.test.quartz.SimpleQuartzJob"/>  
  14.     </bean>  
  15.   
  16.     <!-- 둘.스케줄러의 interval time 설정 -->  
  17.     <!-- 쿼츠에는 아래와 같이 몇초에 한번씩 돌게 하는 Simple type 과 -->  
  18.     <!-- 무슨 요일 몇시에 한번씩 돌게 하는 날짜로 지정하는 Cron type 이 있다. -->  
  19.     <!-- 현재는 Simple type으로 세팅 -->  
  20.     <!-- jobDetail은 위에서 설정한 실제 동작할 클래스 id를 적어준다 -->  
  21.     <!-- startDelay는 서버 시작후 몇초 뒤에 시작할지 세팅(ms 단위)  -->  
  22.     <!-- repeatInterval은 몇 초에 한번씩 실행될 건지 세팅(ms 단위: 현재 1초) -->  
  23.     <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">  
  24.         <property name="jobDetail" ref="simpleQuartzJob"/>  
  25.         <property name="startDelay" value="1000"/>  
  26.         <property name="repeatInterval" value="1000"/>  
  27.     </bean>  
  28.     <!--셋. 실제 동작하게끔 설정 -->  
  29.     <!--ref bean은 위에서 설정한 interval time 아이디를 넣어주면 됨  -->  
  30.     <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
  31.         <property name="triggers">  
  32.             <list>  
  33.                 <ref bean="simpleTrigger"/>  
  34.             </list>  
  35.         </property>  
  36.         <!-- Quartz 실행시 세팅 -->  
  37.         <property name="quartzProperties">  
  38.             <props>  
  39.                 <prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>  
  40.                 <prop key="org.quartz.threadPool.threadCount">5</prop>  
  41.                 <prop key="org.quartz.threadPool.threadPriority">4</prop>  
  42.                 <prop key="org.quartz.jobStore.class">org.quartz.simpl.RAMJobStore</prop>  
  43.                 <prop key="org.quartz.jobStore.misfireThreshold">60000</prop>  
  44.             </props>  
  45.         </property>  
  46.     </bean>  
  47. </beans>  

-Cron : linux 의 Cron tab 과 같은 역할을 하는 타입니다. 즉 몇월, 몇일 몇시에 동작하게 하고 싶으면 Cron type을 사용하시면 됩니다.
<Cron type setting>
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:context="http://www.springframework.org/schema/context"  
  4.        xmlns:p="http://www.springframework.org/schema/p"  
  5.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  6.        xsi:schemaLocation="http://www.springframework.org/schema/beans      
  7.                            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd   
  8.                            http://www.springframework.org/schema/context   
  9.                            http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
  10.     <!--하나. 주기적으로 실행될 클래스 설정 -->  
  11.     <bean id="cronQuartzJob" class="org.springframework.scheduling.quartz.JobDetailBean">  
  12.         <property name="jobClass" value="net.test.quartz.CronQuartzJob"/>  
  13.     </bean>  
  14.        
  15.     <!--둘. 스케줄러의 interval time 설정-->  
  16.     <!--cronExpression을 통해서 스캐줄러 주기를 설정한다. -->  
  17.     <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">  
  18.         <property name="jobDetail" ref="cronQuartzJob"/>  
  19.         <property name="cronExpression" value="0/1 * * * * ?"/>  
  20.     </bean>  
  21.        
  22.     <!--셋. 실제 동작하게끔 설정 -->  
  23.     <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
  24.         <property name="triggers">  
  25.             <list>  
  26.                 <ref bean="cronTrigger"/>  
  27.             </list>  
  28.         </property>  
  29.         <property name="quartzProperties">  
  30.             <props>  
  31.                 <prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>  
  32.                 <prop key="org.quartz.threadPool.threadCount">5</prop>  
  33.                 <prop key="org.quartz.threadPool.threadPriority">4</prop>  
  34.                 <prop key="org.quartz.jobStore.class">org.quartz.simpl.RAMJobStore</prop>  
  35.                 <prop key="org.quartz.jobStore.misfireThreshold">60000</prop>  
  36.             </props>  
  37.         </property>  
  38.     </bean>  
  39. </beans>  


Cron type을 사용하려면 CronExpression을 알아야 합니다.

*Cron Expression
cron expression의 각각의 필드는 다음을 나타낸다.(왼쪽 -> 오른쪽 순)
 필드 이름  허용 값  허용된 특수 문자
 Seconds  0 ~ 59  , - * /
 Minutes  0 ~ 59  , - * /
 Hours  0 ~ 23  , - * /
 Day-of-month  1 ~ 31  , - * ? / L W
 Month  1 ~12 or JAN ~ DEC   , - * /
 Day-Of-Week  1 ~ 7 or SUN-SAT  , - * ? / L #
 Year (optional)  empty, 1970 ~ 2099  , - * /

Cron Expression 의 특수문자
'*' : 모든 수를 나타냄. 분의 위치에 * 설정하면 "매 분 마다" 라는 뜻.
'?' : day-of-month 와 day-of-week 필드에서만 사용가능. 특별한 값이 없음을 나타낸다.
'-' : "10-12" 과 같이 기간을 설정한다. 시간 필드에 "10-12" 이라 입력하면 "10, 11, 12시에 동작하도록 설정" 이란 뜻.
',' : "MON,WED,FRI"와 같이 특정 시간을 설정할 때 사용한다. "MON,WED,FRI" 이면 " '월,수,금' 에만 동작" 이란 뜻.
'/' : 증가를 표현합니다. 예를 들어 초 단위에 "0/15"로 세팅 되어 있다면 "0초 부터 시작하여 15초 이후에 동작" 이란 뜻.
'L' : day-of-month 와 day-of-week 필드에만 사용하며 마지막날을 나타냅. 만약 day-of-month 에 "L" 로 되어 있다면 이번 달의 마지막에 실행하겠다는 것을 나타냄.
'W' : day-of-month 필드에만 사용되며, 주어진 기간에 가장 가까운 평일(월~금)을 나타낸다. 만약 "15W" 이고 이번 달의 15일이 토요일이라면 가장가까운 14일 금요일날 실행된다. 또 15일이 일요일이라면 가장 가까운 평일인 16일 월요일에 실행되게 된다. 만약 15일이 화요일이라면 화요일인 15일에 수행된다.
"LW" : L과 W를 결합하여 사용할 수 있으며 "LW"는 "이번달 마지막 평일"을 나타냄
"#" : day-of-week에 사용된다. "6#3" 이면 3(3)번째 주 금요일(6) 이란 뜻이된다.1은 일요일 ~ 7은 토요일 

 Expression  Meaning
 "0 0 12 * * ?"  매일 12시에 실행
 "0 15 10 ? * *"  매일 10시 15분에 실행
 "0 15 10 * * ?"  매일 10시 15분에 실행
 "0 15 10 * * ? *"  매일 10시 15분에 실행
 "0 15 10 * * ?  2010"   2010년 동안 매일 10시 15분에 실행
 "0 * 14 * * ?"  매일 14시에서 시작해서 14:59분 에 끝남
 "0 0/5 14 * * ?"  매일 14시에 시작하여 5분 간격으로 실행되며 14:55분에 끝남
 "0 0/5 14,18 * * ?"  매일 14시에 시작하여 5분 간격으로 실행되며 14:55분에 끝나고, 매일 18시에 시작하여 5분간격으로 실행되며 18:55분에 끝난다.
 "0 0-5 14 * * ?"  매일 14시에 시작하여 14:05 분에 끝난다.

* 시간에 맞춰 돌아가는 스케줄러에서 다른 클래스를 사용하고 싶을 때는 다음과 같이 설정합니다.
  1. <!-- 스프링 DI : 사용할 Service 객체를 생성 -->  
  2. <bean id="quartzJobService" class="net.test.quartz.service.impl.QuartzJobServiceImpl"/>  
  3.   
  4. <bean id="simpleQuartzJob" class="org.springframework.scheduling.quartz.JobDetailBean">  
  5.     <property name="jobClass" value="net.test.quartz.SimpleQuartzJob"/>  
  6.     <!-- 사용하고자 하는 class의 bean id를 등록 -->  
  7.     <property name="jobDataAsMap">  
  8.         <map>  
  9.             <entry key="quartzJobService">  
  10.                 <ref local="quartzJobService"/>  
  11.             </entry>  
  12.         </map>  
  13.     </property>  
  14. </bean>  

 *두가지 스케줄러를 동시에 실행 시킬때
  1. <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
  2.     <property name="triggers">  
  3.         <!--트리거를 두개 생성후 아래와 같이 세팅 -->  
  4.         <list>  
  5.             <ref bean="simpleTrigger"/>  
  6.             <ref bean="cronTrigger"/>  
  7.         </list>  
  8.     </property>  
  9.     <property name="quartzProperties">  
  10.         <props>  
  11.             <prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>  
  12.                 <prop key="org.quartz.threadPool.threadCount">5</prop>  
  13.                 <prop key="org.quartz.threadPool.threadPriority">4</prop>  
  14.                 <prop key="org.quartz.jobStore.class">org.quartz.simpl.RAMJobStore</prop>  
  15.                 <prop key="org.quartz.jobStore.misfireThreshold">60000</prop>  
  16.         </props>  
  17.     </property>  
  18. </bean>  


7) 실제 작동할 Class파일 생성
  1. package net.test.quartz;   
  2.   
  3. import net.test.quartz.service.QuartzJobService;   
  4.   
  5. import org.quartz.JobExecutionContext;   
  6. import org.quartz.JobExecutionException;   
  7. import org.springframework.scheduling.quartz.QuartzJobBean;   
  8.   
  9. public class SimpleQuartzJob extends QuartzJobBean{   
  10.     //실행될 클래스는 꼭 QuartzJobBean을 상속받아야 되며    
  11.     //executeInternal method를 override 하면 자동으로 이 메소드가 실행   
  12.   
  13.     //Spring의 DI를 사용하여 Service객체를 setting   
  14.     //DI를 사용하지 않는다면 필요 없는 부분   
  15.     private QuartzJobService quartzJobService;   
  16.     public void setQuartzJobService(QuartzJobService quartzJobService) {   
  17.         this.quartzJobService = quartzJobService;   
  18.     }   
  19.   
  20.   
  21.     @Override  
  22.     protected void executeInternal(JobExecutionContext ex)throws JobExecutionException {   
  23.         quartzJobService.printLog();   
  24.     }   
  25.        
  26. }  


위와 같은 방식으로 Spring과 Quartz를 사용하여 스케줄러를 사용할 수 있습니다.

함께 업로드 하는 파일은 제가 직접 작업한 프로젝트이구요. 함께 확인 해 보시면 쉽게 쿼츠를 사용하실수 있으실 겁니다.~^^



출처 : http://javastore.tistory.com/96


EHCache를 이용한 기본적인 캐시 구현 방법 및 분산 캐시 구현 방법을 살펴본다.

EHCache의 주요 특징 및 기본 사용법

게시판이나 블로그 등 웹 기반의 어플리케이션은 최근에 사용된 데이터가 또 다시 사용되는 경향을 갖고 있다. 80:20 법칙에 따라 20%의 데이터가 전체 조회 건수의 80%를 차지할 경우 캐시를 사용함으로써 성능을 대폭적으로 향상시킬 수 있을 것이다.

본 글에서는 캐시 엔진 중의 하나인 EHCache의 사용방법을 살펴보고, Gaia 시스템에서 EHCache를 어떻게 사용했는 지 살펴보도록 하겠다.

EHCache의 주요 특징

EHCache의 주요 특징은 다음과 같다.

  • 경량의 빠른 캐시 엔진
  • 확장(scable) - 메모리 & 디스크 저장 지원, 멀티 CPU의 동시 접근에 튜닝
  • 분산 지원 - 동기/비동기 복사, 피어(peer) 자동 발견
  • 높은 품질 - Hibernate, Confluence, Spring 등에서 사용되고 있으며, Gaia 컴포넌트에서도 EHCache를 사용하여 캐시를 구현하였다.
기본 사용법

EHCache를 사용하기 위해서는 다음과 같은 작업이 필요하다.

  1. EHCache 설치
  2. 캐시 설정 파일 작성
  3. CacheManager 생성
  4. CacheManager로부터 구한 Cache를 이용한 CRUD 작업 수행
  5. CacheManager의 종료
EHCache 설치

EHCache 배포판은 http://ehcache.sourceforge.net/ 사이트에 다운로드 받을 수 있다. 배포판의 압축을 푼 뒤, ehcache-1.2.x.jar 파일이 생성되는 데, 이 파일을 클래스패스에 추가해준다. 또한, EHCache는 자카르타의 commons-logging API를 사용하므로, commons-logging과 관련된 jar 파일을 클래스패스에 추가해주어야 한다.

ehcache.xml 파일

EHCache는 기본적으로 클래스패스에 존재하는 ehcache.xml 파일로부터 설정 파일을 로딩한다. 가장 간단한 ehcache.xml 파일은 다음과 같이 작성할 수 있다.

<ehcache>
    <diskStore path="java.io.tmpdir"/>

    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
            />
    
    <cache name="simpleBeanCache"
            maxElementsInMemory="10"
            eternal="false"
            overflowToDisk="false"
            timeToIdleSeconds="300"
            timeToLiveSeconds="600"
            memoryStoreEvictionPolicy="LRU" />

</ehcache>

위 코드에서 <defaultCache> 태그는 반드시 존재해야 하는 태그로서, 코드에서 캐시를 직접 생성할 때 사용되는 캐시의 기본 설정값을 저장한다. <cache> 태그는 하나의 캐시를 지정할 때 사용된다. name 속성은 캐시의 이름을 지정하며, 코드에서는 이 캐시의 이름을 사용하여 사용할 Cache 인스턴스를 구한다.

설정 파일에 대한 자세한 내용은 뒤에서 살펴보기로 하자.

CacheManager 생성

ehcache.xml 파일을 작성했다면 그 다음으로 할 작업은 net.sf.ehcache.CacheManager 객체를 생성하는 것이다. CacheManager 객체는 다음의 두 가지 방법 중 한가지 방식을 사용하여 생성할 수 있다.

  • CacheManager.create() : 싱글톤 인스턴스 사용
  • new CacheManager() : 새로운 CacheManager 인스턴스 생성
CacheManager.create() 메소드는 싱글톤 인스턴스를 생성하기 때문에 최초에 한번 호출될 때에만 CacheManager의 초기화 작업이 수행되며, 이후에는 동일한 CacheManager 인스턴스를 리턴하게 된다. 아래는 CacheManager.create() 메소드의 사용 예이다.

CacheManager cacheManager = CacheManager.create();

싱글톤 인스턴스가 아닌 직접 CacheManager 객체를 조작하려면 다음과 같이 new를 사용하여 CacheManager 인스턴스를 생성해주면 된다.

CacheManager cacheManager = new CacheManager();

두 방식 모두 클래스패스에 위치한 ehcache.xml 파일로부터 캐시 설정 정보를 로딩한다.

만약 클래스패스에 위치한 ehcache.xml 파일이 아닌 다른 설정 파일을 사용하고 싶다면 다음과 같이 URL, InputStream, 또는 String(경로) 객체를 사용하여 설정 파일의 위치를 지정할 수 있다.

URL configFile = this.getClass().getResource("/ehcache_config_replicate.xml")
CacheManager cacheManager = new CacheManager(configFile);

Cache에 CRUD 수행

CacheManager 인스턴스를 생성한 다음에는 CacheManager 인스턴스로부터 Cache 인스턴스를 구하고, Cache 인스턴스를 사용하여 객체에 대한 캐시 작업을 수행할 수 있게 된다.

Cache 구하기
net.sf.ehcache.Cache 인스턴스는 CacheManager.getCache() 메소드를 사용하여 구할 수 있다.

CacheManager cacheManager = new CacheManager(configFileURL);
Cache cache = cacheManager.getCache("simpleBeanCache");

CacheManager.getCache() 메소드에 전달되는 파라미터는 ehcache.xml 설정 파일에서 <cache> 태그의 name 속성에 명시한 캐시의 이름을 의미한다. 지정한 이름의 Cache 인스턴스가 존재하지 않을 경우 CacheManager.getCache() 메소드는 null을 리턴한다.

Create/Update 작업 수행
Cache 인스턴스를 구한 다음에는 Cache.put() 메소드를 사용하여 캐시에 객체를 저장할 수 있다. 아래 코드는 Cache.put() 메소드의 사용예이다.

Cache cache = cacheManager.getCache("simpleBeanCache");

SimpleBean newBean = new SimpleBean(id, name);
Element newElement = new Element(newBean.getId(), newBean);
cache.put(newElement);

Cache.put() 메소드는 net.sf.ehcache.Element 객체를 전달받는다. Element 클래스는 캐시에 저장될 원소를 나타내며, 키와 값을 사용하여 원소를 표현한다. Element 객체를 생성할 때 첫번째 파라미터는 원소의 키를 의미하며, 두번째 파라미터는 원소의 값을 의미한다.

EHCache는 캐시에 저장될 각각의 객체들을 키를 사용하여 구분하기 때문에, Element 객체를 생성할 때 (의미상) 서로 다른 객체는 서로 다른 키를 사용해야 한다.

Map과 마찬가지로 EHCache가 제공하는 Cache는 삽입을 하거나 기존의 값을 수정할 때 모두 Cache.put() 메소드를 사용한다. 기존에 캐시에 저장된 객체를 수정하길 원한다면 다음과 같이 동일한 키를 사용하는 Element 객체를 Cache.put() 메소드에 전달해주면 된다.

Element newElement = new Element(id, someBean);
cache.put(newElement);
...
Element updatedElement = new Element(id, updatedBean);
cache.put(updatedElement);

Read 작업 수행
Cache에 보관된 객체를 사용하려면 Cache.get() 메소드를 사용하면 된다. Cache.get() 메소드는 키를 파라미터로 전달받으며, 키에 해당하는 Element 객체를 리턴하며 관련 Element과 존재하지 않을 경우 null을 리턴한다. 아래 코드는 Cache.get() 메소드의 사용예이다.

Element element = cache.get(key);
SimpleBean bean = (SimpleBean) element.getValue();

Element.getValue() 메소드는 캐시에 저장된 객체를 리턴한다. 만약 Serializable 하지 않은 객체를 값으로 저장했다면 다음과 같이 Element.getObejectValue() 메소드를 사용하여 값을 구해야 한다.

Element element = cache.get(key);
NonSerializableBean bean = (NonSerializableBean) element.getObjectValue();

Delete 작업 수행
Cache에 보관된 객체를 삭제하려면 Cache.remove() 메소드를 사용하면 된다. 아래 코드는 Cache.remove() 메소드의 사용예이다.

boolean deleted = cache.remove(key);

Cache.remove() 메소드는 키에 해당하는 객체가 존재하여 삭제한 경우 true를 리턴하고, 존재하지 않은 경우 false를 리턴한다.

CacheManager의 종료

사용이 종료된 CacheManager는 다음과 같이 shutdown() 메소드를 호출하여 CacheManager를 종료해야 한다.

cacheManager.shutdown();

Cache 값 객체 사용시 주의사항

캐시에 저장되는 객체는 레퍼런스가 저장된다. 따라서, 동일한 키에 대해 Cache.put()에 전달한 Element의 값과Cache.get()으로 구한 Element의 값은 동일한 객체를 참조하게 된다.

SimpleBean bean = ...;
Element element = new Element(key, bean);
cache.put(element);

Element elementFromCache = cache.get(key);
SimpleBean beanFromCache = (SimpleBean)elementFromCache.getValue();

(bean == beanFromCache); // true
(element == elementFromCache); // false

위 코드에서 Cache.put()에 전달된 element 객체와 Cache.get()으로 구한 elementFromCache 객체는 서로 다른 객체이다. 하지만, 두 Element 객체가 갖고 있는 값은 동일한 객체를 참조하고 있다. 따라서, 캐시에 값으로 저장된 객체를 변경하게 되면 캐시에 저장된 내용도 변경되므로, 캐시 사용시 이 점에 유의해야 한다.

캐시 설정

캐시 설정 파일에 <cache> 태그를 이용하여 캐시를 설정했었다. 캐시 설정과 관련하여 <cache> 태그는 다양한 속성을 제공하고 있는데, 이들 속성에는 다음과 같은 것들이 존재한다.

name 캐시의 이름 필수
maxElementsInMemory 메모리에 저장될 수 있는 객체의 최대 개수 필수
eternal 이 값이 true이면 timeout 관련 설정은 무시되고, Element가 캐시에서 삭제되지 않는다. 필수
overflowToDisk 메모리에 저장된 객체 개수가 maxElementsInMemory에서 지정한 값에 다다를 경우 디스크에 오버플로우 되는 객체는 저장할 지의 여부를 지정한다. 필수
timeToIdleSeconds Element가 지정한 시간 동안 사용(조회)되지 않으면 캐시에서 제거된다. 이 값이 0인 경우 조회 관련 만료 시간을 지정하지 않는다. 기본값은 0이다. 선택
timeToLiveSeconds Element가 존재하는 시간. 이 시간이 지나면 캐시에서 제거된다. 이 시간이 0이면 만료 시간을 지정하지 않는다. 기본값은 0이다. 선택
diskPersistent VM이 재 가동할 때 디스크 저장소에 캐싱된 객체를 저장할지의 여부를 지정한다. 기본값은 false이다. 선택
diskExpiryThreadIntervalSeconds Disk Expiry 쓰레드의 수행 시간 간격을 초 단위로 지정한다. 기본값은 120 이다. 선택
memoryStoreEvictionPolicy 객체의 개수가 maxElementsInMemory에 도달했을 때,모메리에서 객체를 어떻게 제거할 지에 대한 정책을 지정한다. 기본값은 LRU이다. FIFO와 LFU도 지정할 수 있다. 선택

아래 코드는 몇 가지 설정 예이다.

<!--
sampleCache1 캐시. 최대 10000개의 객체를 저장할 수 있으며, 
5분 이상 사용되지 않거나 또는 10분 이상 캐시에 저장되어 있을 경우 
캐시에서 제거된다. 저장되는 객체가 10000개를 넘길 경우, 
디스크 캐시에 저장한다.
-->
<cache name="sampleCache1"
       maxElementsInMemory="10000"
       maxElementsOnDisk="1000"
       eternal="false"
       overflowToDisk="true"
       timeToIdleSeconds="300"
       timeToLiveSeconds="600"
       memoryStoreEvictionPolicy="LFU"
       />

<!--
sampleCache2 캐시. 최대 1000개의 객체를 저장한다. 
오버플로우 된 객체를 디스크에 저장하지 않기 때문에 
캐시에 최대 개수는 1000개이다. eternal이 true 이므로, 
timeToLiveSeconds와 timeToIdleSeconds 값은 무시된다.
-->
<cache name="sampleCache2"
       maxElementsInMemory="1000"
       eternal="true"
       overflowToDisk="false"
       memoryStoreEvictionPolicy="FIFO"
       />

<!--
sampleCache3 캐시. 오버플로우 되는 객체를 디스크에 저장한다.
디스크에 저장된 객체는 VM이 재가동할 때 다시 캐시로 로딩된다.
디스크 유효성 검사 쓰레드는 10분 간격으로 수행된다.
-->
<cache name="sampleCache3"
       maxElementsInMemory="500"
       eternal="false"
       overflowToDisk="true"
       timeToIdleSeconds="300"
       timeToLiveSeconds="600"
       diskPersistent="true"
       diskExpiryThreadIntervalSeconds="600"
       memoryStoreEvictionPolicy="LFU"
       />

분산 캐시

EHCache는 분산 캐시를 지원한다. EHCache는 피어(peer) 자동 발견 및 RMI를 이용한 클러스터간 데이터 전송의 신뢰성 등 분산 캐시를 위한 완전한 기능을 제공하고 있다. 또한, 다양한 옵션을 통해 분산 상황에 맞게 설정할 수 있도록 하고 있다.

참고로, EHCache는 RMI를 이용하여 분산 캐시를 구현하고 있기 때문에, Serializable 한 객체만 분산 캐시에서 사용 가능하다. 키 역시 Serializable 해야 한다.

분산 캐시 구현 방식

EHCache는 한 노드의 캐시에 변화가 생기면 나머지 노드에 그 변경 내용을 전달하는 방식을 사용한다. 즉, 클러스터에 있는 캐시 인스턴스가 n개인 경우, 한번의 변경에 대해 n-1개의 변경 통지가 발생한다.

각 노드의 캐시간 데이터 전송은 RMI를 통해서 이루어진다. EHCache가 데이터 전송 기술로서 RMI를 사용하는 이유는 다음과 같다.

  • 자바에서 기본적으로 제공하는 원격 메커니즘
  • 안정화된 기술
  • TCP 소켓 옵션을 튜닝할 수 있음
  • Serializable 한 객체를 지원하기 때문에, 데이터 전송을 위해 XML과 같은 별도의 포맷으로 변경할 필요가 없음
노드 발견

EHCache는 클러스터에 새로운 노드가 추가돌 경우 해당 노드를 자동적으로 발견하는 방식과, 지정된 노드 목록에 대해서만 클러스터의 노드로 사용하는 방식을 지원하고 있다.

멀티캐스트 방식

멀티캐스트 모드를 사용한 경우, 지정한 멀티캐스트 IP(224.0.0.1~239.255.255.255)와 포트에 참여하는 노드를 자동으로 발견하게 된다. 지정한 IP와 포트에 참여한 노드는 자기 자신을 다른 노드에 통지한다. 이 방식을 사용하면 클러스터에 동적으로 노드를 추가하거나 제거할 수 있다.

노드 목록 지정 방식

클러스터에 포함되는 노드 목록을 지정한다. 동적으로 새로운 노드를 추가하거나 기존 노드를 제거할 수 없다.

분산 캐시 설정

분산 캐시를 사용하기 위해서는 다음과 같은 세 개의 정보를 지정해주어야 한다.

  • CacheManagerPeerProvider - 피어 발견 관련 설정
  • CacheManagerPeerListener - 메시지 수신 관련 설정
  • 캐시별 CacheReplicator - 메시지 생성 규칙 설정
CacheManagerPeerProvider 설정

CacheManagerPeerProvider는 새롭게 추가된 노드를 발견하는 방식을 지정한다.

노드를 자동으로 발견하는 멀티캐스트 방식을 사용하려면 다음과 같이 설정한다.

<cacheManagerPeerProviderFactory
    class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
    properties="peerDiscovery=automatic, 
                    multicastGroupAddress=230.0.0.100, multicastGroupPort=1234" />

위 코드에서 properties 속성의 값에 사용된 프로퍼티는 다음과 같다.

peerDiscovery automatic으로 지정하면 멀티캐스트 방식을 사용한다.
multicaseGroupAddress 멀티캐스트 IP
multicaseGroupPort 포트 번호

하나의 클러스터에 포함될 노드들은 동일한 멀티캐스트 IP와 포트 번호를 사용해야 한다.

클러스터에 참여할 노드 목록을 지정하는 IP 방식을 사용하려면 다음과 같이 설정한다.

<cacheManagerPeerProviderFactory
    class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
    properties="peerDiscovery=manual, 
                    rmiUrls=//server2:12345/cache1|//server2:12345/cache2" />

위 코드에서 properties 속성의 값에 사용된 프로퍼티는 다음과 같다.

peerDiscovery manual로 지정한 IP 지정 방식이다.
rmiUrls 분산 노드에 참여할 서버 및 캐시 목록을 지정한다. 현재 노드의 정보는 포함시켜서는 안 된다.

이 경우, rmiUrls에 명시된 포트 번호는 뒤에 살펴볼 CacheManagerPeerListener가 사용할 포트 번호를 지정해주어야 한다.

CacheManagerPeerListener 설정

노드를 발견하는 방식을 지정했다면, 다음으로 할 작업은 클러스터에 있는 다른 노드에서 발생한 변경 정보를 수신할 때 사용할 포트 번호를 지정하는 것이다. 다음과 같은 코드를 이용하여 수신과 관련된 포트 번호를 설정할 수 있다.

<cacheManagerPeerListenerFactory
    class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
    properties="port=12345, socketTimeoutMillis=120000" />

위 코드에서 properties 속성의 값에 사용된 프로퍼티는 다음과 같다.

port 메시지를 수신할 때 사용되는 포트
socketTimeoutMillis 이 노드에 메시지를 보냈을 때 메시지 전송을 기다리는 시간. 기본값은 2000ms.

캐시별 CacheReplicator 설정

분산 환경에 적용되어야 하는 캐시는 캐시의 내용이 변경되었을 때 다른 노드에 있는 캐시에 변경 내역을 알려주어야 한다. <cacheEventListenerFactory> 태그를 사용하면, 언제 어떻게 캐시의 변경 내역을 통지할지의 여부를 지정할 수 있다. 아래 코드는 설정의 예이다.

<cache name="simpleBean"
      maxElementsInMemory="100"
      eternal="false"
      overflowToDisk="false"
      timeToIdleSeconds="300"
      timeToLiveSeconds="600"
      memoryStoreEvictionPolicy="LRU">
       <cacheEventListenerFactory 
           class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" 
           properties="replicateUpdatesViaCopy=true,replicateUpdates=true" />
</cache>

위 코드와 같이 <cacheEventListenerFactory>의 구현 클래스로 RMICacheReplicatorFactory를 지정하면 캐시에 변경이 생길 때 마다 해당 변경 내역을 클러스터에 참여하고 있는 노드의 캐시에 통지하게 된다. properties 속성에 프로퍼티를 지정하면, 캐시 요소의 추가, 변경, 삭제 등에 대해 통지 방식을 적용할 수 있다. 설정할 수 있는 프로퍼티는 다음과 같다.

replicatePuts 캐시에 새로운 요소가 추가됐을 때 다른 노드에 복사할지의 여부
replicateUpdates 캐시 요소의 값이 변경되었을 때 다른 노드에 값을 복사할지의 여부
replicateRemovals 캐시 요소가 삭제되었을 때 다른 노드에 반영할지의 여부
replicateAsynchronously 비동기로 값을 복사할지의 여부
replicateUpdatesViaCopy 새로운 요소를 다른 노드에 복사할 지 아니면 삭제 메시지를 보낼지의 여부
asynchronousReplicationIntervalMillis 비동기 방식을 사용할 때 변경 내역을 다른 노드에 통지하는 주기. 기본값은 1000.

위 속성의 기본값은 모두 true이다. 따라서, 기본 설정값을 사용하려면 다음과 같이 properties 속성을 사용하지 않아도 된다.

<cache name="simpleBean" ...
      memoryStoreEvictionPolicy="LRU">
       <cacheEventListenerFactory 
           class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" />
</cache>

어플리케이션 구동시 캐시 데이터 로딩하기

CacheManager가 초기화 될 때, 클러스터에 있는 다른 캐시로부터 데이터를 로딩할 수 있다. 이는 초기 구동이 완료된 후 곧 바로 서비스를 제공할 수 있음을 의미한다. 초기 구동시 다른 노드로부터 캐시 데이터를 로딩하려면 다음과 같이 <bootstrapCacheLoaderFactory> 태그의 구현 클래스를 RMIBootstrapCacheLoaderFactory로 지정해주면 된다.

<cache name="simpleBean" ...
      memoryStoreEvictionPolicy="LRU">
       <bootstrapCacheLoaderFactory
           class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"
           properties="bootstrapAsynchronously=true,
                       maximumChunkSizeBytes=5000000" />

       <cacheEventListenerFactory 
           class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" />
</cache>

RMIBootstrapCacheLoaderFactory에 전달 가능한 프로퍼티 목록은 다음과 같다.

bootstrapAsynchronously 비동기적으로 수행할지의 여부를 지정
maximumChunkSizeBytes 클러스터의 다른 노드로부터 로딩 가능한 데이터의 최대 크기

RMIBoostrapCacheLoaderFactory를 설정하면 캐시를 초기화 할 때, 원격지 노드의 캐시에 저장된 데이터를 로딩하여 로컬 캐시에 저장한다.

분산 캐시 고려사항

분산 캐시를 사용할 때에는 다음과 같은 내용을 고려해야 한다.

  • 노드 증가에 따라 네트워크 트래픽 증가:
    많은 양의 네트워크 트래픽이 발생할 수 있다. 특히 동기 모드인 경우 성능에 영향을 받을 수 있다. 비동기 모드인 경우 버퍼에 변경 내역을 저장하였다가 일정한 주기로 버퍼에 쌓인 내역을 다른 노드에 통지하기 때문에 이 문제를 다소 완하시킬 수 있다.
  • 데이터 불일치 발생 가능성:
    두 노드에서 동시에 동일한 캐시의 동일한 데이터에 대한 변경을 수행할 경우, 두 노드 사이에 데이터 불일치가 발생할 수 있다. 캐시 데이터의 불일치가 매우 심각한 문제가 될 경우, 동기 모드(replicateAsynchronously=false)와 복사 메시지 대신 삭제 메시지를 전송(replicateUpdatesViaCopy=false)함으로써 이 문제를 해결할 수 있다.
관련링크:

참조 : http://javacan.tistory.com/123


annotation으로 javaBean의 중북되고 반복되는 코드를 한결 편리하게 사용할 수 있는 유틸이 있네요.
getter, setter, toString, hasCode등과 같이 bean을 만들때 매번 불편하고 가독성 없이 추가만 해주었는데
이 유틸리티를 사용하면 이런 불편함이 많이 줄어들것으로 생각이 됩니다.
딱히 javaBean이 아니라 다른곳에서도 유용하게 사용하실 수 있습니다.
사용법및 설치법은 다른 여러가지 방법으로도 사용을 할 수 있다고 하나 이클립스에서 설정하는 법을 설명하겠습니다.

다운로드 : http://projectlombok.org/
설치방법 : 해당 사이트에서 lombok.jar 파일을 다운받은 후 console에서 다운로드 경로로 이동한 다음 
java -jar lombok.jar 명령을 입력하게 되면 GUI 창이 노출이 됩니다. 해당 창이 노출이 되면 eclipse 파일의 경로를 지정하고
install/update 버튼을 선택하기면 하면 설치가 끝납니다.

사용방법 : http://www.ibm.com/developerworks/kr/library/os-lombok/index.html