Statement Caching
Statement Caching#
Statement Caching은 동일한 SQL statement를 반복적으로 수행할 때, 해당 statement를 캐싱하여 성능을 개선할 수 있는 기능이다. Statement Caching을 이용하기 위해서는 기존 프로그램의 수정없이 관련 연결 속성만 설정하면 된다. 캐싱의 대상은 PreparedStatement, CallableStatement 객체이며, Statement 객체는 캐싱하지 않는다. Statement Caching은 연결(Connection) 단위로 설정 및 관리된다.
기본 동작#
Statement 인터페이스의 close() 메소드를 실행하면 statement가 캐싱되고, prepareStatement() 또는 prepareCall() 메소드를 실행할 때 캐시된 statement에서 일치하는 statement를 검색한다. 일치하는 statement가 캐시에 있으면 해당 Statement 객체를 반환하고, 없으면 새로운 Statement 객체를 생성하여 반환한다.
캐시된 statement와 동일한 statement로 간주되는 조건은 다음과 같다.
- SQL문이 동일할 것
- PreparedStatement 또는 CallableStatement와 같은 statement type이 동일 할 것
- 해당 statement가 생성한 ResultSet 객체의 속성(Scrollable, Concurrency, Holdability)이 동일할 것
Statement Caching 기능이 활성화되어있는 경우 Statement 인터페이스의 close() 메소드 수행 시, statement가 캐싱되기 때문에 statement는 물리적으로 close 되지 않는다.
그러나 아래의 경우에는 statement가 물리적으로 close 된다.
-
Connection 인터페이스의 close() 메소드 수행 시
해당 connection에서 생성한 모든 statement 객체가 물리적으로 close 된다. 그러나 pooled connection의 경우는 물리적으로 close되지 않는다.
-
isPoolable() 메소드값이 false인 statement의 객체를 close 하는 경우
isPoolable() 메소드값이 false인 경우 캐싱되지 않으므로 그 statement 객체는 물리적으로 close된다.
-
stmt_cache_size 설정값을 초과하여 캐싱이 시도되는 경우
LRU 알고리즘에 의해 가장 오랫동안 접근되지 않은 statement 객체는 물리적으로 close 된다.
사용법#
Statement Caching을 사용하기 위해서는 아래의 연결 속성을 설정해야 한다. 각 연결 속성에 대한 자세한 설명은 1장. JDBC 시작하기 > 연결 속성 정보를 참고한다.
-
stmt_cache_enable의 기본값은 false 이므로, Statement Caching 기능을 사용하기 위해서는 아래와 같이 설정해야 한다.
Properties sProps = new Properties(); ... sProps.put("stmt_cache_enable", "true"); ...
-
만약, Statement Caching 활성화 상태에서 특정 statement를 캐싱하지 않으려면, Statement 인터페이스의 setPoolable(false) 메소드를 수행해야 한다.
... sStmt.setPoolable(false); ...
코드 예제#
아래의 예제와 같이 특정 SQL을 반복적으로 수행해야 할 때, Statement Caching 기능을 활성화하면 캐시된 statement를 재사용함으로써 성능 향상을 기대할 수 있다.
...
Properties sProps = new Properties();
...
sProps.put("stmt_cache_enable", "true");
...
Connection sCon = DriverManager.getConnection( sURL, sProps );
Statement sStmt = sCon.createStatement();
...
for (int i = 0; i < 100; i++)
{
PreparedStatement sPreStmt = sCon.prepareStatement( "INSERT INTO T1 VALUES(1,1)" );
sPreStmt.execute();
sPreStmt.close();
}
/* Finalize process */
sStmt.close();
sCon.close();
...
주의 사항#
- Statement Caching 기능이 활성화된 상태에서 데이터베이스 객체에 DDL을 수행하면 execute시에 에러가 발생할 수 있으므로 주의가 필요하다.
- Statement Caching 기능은 defer_prepares 기능과 함께 사용할 수 없다.
- Statement Caching 기능을 DBCP의 poolPreparedStatement와 같은 다른 라이브러리에서 제공하는 statement pooling 기능과 중복 사용하지 않도록 주의해야 한다.
- Statement Caching 기능을 사용하면 서버와 클라이언트의 메모리 사용량이 증가할 수 있다. 이는 stmt_cache_size와 stmt_cache_sql_limit 속성을 적절히 조절하여 튜닝하는 것을 권장한다. 필요 시 자바 힙(heap) 메모리 크기 설정도 함께 고려한다.