데이터베이스 성능 최적화를 위한 캐시의 필요성
데이터베이스(DB) 작업은 물리적 디스크 I/O를 수반하기 때문에 메모리 내 연산보다 속도가 훨씬 느립니다. 빈번하게 발생하는 동일한 쿼리 요청을 매번 DB에서 처리하는 것은 시스템 자원을 낭비하는 일입니다. MyBatis는 이러한 성능 병목을 해결하기 위해 조회 결과를 메모리에 보관하고 재사용하는 캐시 시스템을 제공합니다.
1. 1차 캐시 (SqlSession 레벨 캐시)
1차 캐시는 SqlSession 생명주기와 궤를 같이하는 로컬 캐시입니다. 별도의 설정 없이도 기본적으로 활성화되어 있으며, 동일한 SqlSession 내에서 같은 조건의 쿼리를 실행할 경우 DB를 거치지 않고 메모리에서 결과를 반환합니다.
1차 캐시의 핵심 메커니즘
1차 캐시는 BaseExecutor 클래스에서 관리됩니다. 내부적으로 PerpetualCache라는 객체를 사용하며, 이는 단순히 HashMap을 활용하여 데이터를 저장하는 구조입니다.
// 1차 캐시 조회 로직의 단순화된 형태
public <E> List<E> executeQuery(MappedStatement ms, Object parameter, RowBounds rb, ResultHandler rh, CacheKey key, BoundSql sql) {
if (this.isClosed) {
throw new ExecutorException("Executor가 종료되었습니다.");
}
// flushCache="true" 설정 시 캐시 초기화
if (queryDepth == 0 && ms.isFlushCacheRequired()) {
clearLocalCache();
}
List<E> resultSet;
try {
queryDepth++;
// 캐시에서 데이터 확인
resultSet = (List<E>) localCache.getObject(key);
if (resultSet != null) {
handleCachedParameters(ms, key, parameter, sql);
} else {
// 캐시에 없으면 DB에서 조회
resultSet = fetchFromDatabase(ms, parameter, rb, rh, key, sql);
}
} finally {
queryDepth--;
}
// LocalCacheScope가 STATEMENT인 경우 매 쿼리 후 캐시 삭제
if (queryDepth == 0 && configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
clearLocalCache();
}
return resultSet;
}
캐시 적중 여부를 결정하는 CacheKey
MyBatis는 다음 네 가지 조건을 조합하여 CacheKey를 생성하고, 두 쿼리가 동일한지 판단합니다.
- 실행되는 매퍼의 Namespace와 쿼리의 ID
- 페이징 처리를 위한 RowBounds(Offset, Limit)
- 실행되는 SQL 구문 자체
- 전달된 파라미터의 실제 값
// CacheKey 생성 로직의 구조
public CacheKey generateKey(MappedStatement ms, Object param, RowBounds rb, BoundSql sql) {
CacheKey identifier = new CacheKey();
identifier.update(ms.getId());
identifier.update(rb.getOffset());
identifier.update(rb.getLimit());
identifier.update(sql.getSql());
// 파라미터 값들을 루프하며 식별자에 추가
List<ParameterMapping> mappings = sql.getParameterMappings();
for (ParameterMapping mapping : mappings) {
Object value = getParameterValue(param, mapping);
identifier.update(value);
}
return identifier;
}
2. 2차 캐시 (Mapper 레벨 캐시)
2차 캐시는 Mapper Namespace 단위로 작동하며, 여러 SqlSession이 동일한 캐시를 공유할 수 있습니다. 애플리케이션의 생명주기와 함께하므로 1차 캐시보다 더 오래 지속됩니다. 2차 캐시가 활성화되어 있다면 MyBatis는 1차 캐시보다 2차 캐시를 먼저 조회합니다.
2차 캐시 설정 방법
전역 설정 파일에서 캐시를 활성화한 후, 개별 Mapper XML 파일에 <cache/> 태그를 추가해야 합니다.
<!-- mybatis-config.xml -->
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
<cache eviction="LRU" flushInterval="60000" size="512" readOnly="true"/>
</mapper>
CachingExecutor의 작동 원리
2차 캐시는 CachingExecutor에 의해 처리되며, 데코레이터 패턴을 통해 기존 Executor 기능을 확장합니다.
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rb, ResultHandler rh, CacheKey key, BoundSql sql) {
Cache secondaryCache = ms.getCache();
if (secondaryCache != null) {
// 필요 시 캐시 플러시 처리
flushCacheIfRequired(ms);
if (ms.isUseCache() && rh == null) {
// 트랜잭션 캐시 매니저를 통해 접근
List<E> cachedList = (List<E>) tcm.getObject(secondaryCache, key);
if (cachedList == null) {
// 1차 캐시 또는 DB 조회로 위임
cachedList = delegate.query(ms, parameter, rb, rh, key, sql);
tcm.putObject(secondaryCache, key, cachedList);
}
return cachedList;
}
}
return delegate.query(ms, parameter, rb, rh, key, sql);
}
3. 주의사항 및 한계
2차 캐시는 성능 향상에 도움이 되지만, 데이터 무결성 문제가 발생할 수 있는 치명적인 단점이 있습니다. 2차 캐시는 Namespace 단위로 관리되기 때문에, 여러 테이블을 조인하여 조회하는 쿼리가 있는 경우 문제가 생길 수 있습니다.
- 상황: Mapper A에서 Table A와 Table B를 조인하여 조회한 결과를 캐싱함.
- 문제: Mapper B에서 Table B의 데이터를 수정함.
- 결과: Mapper A의 캐시는 Table B가 수정되었음을 알지 못하므로, 여전히 과거의(Dirty) 데이터를 반환함.
따라서 2차 캐시를 안전하게 사용하려면 모든 연관된 CUD(Create, Update, Delete) 작업이 동일한 Namespace 내에서 이루어지도록 설계하거나, 캐시 의존 관계를 세밀하게 관리해야 합니다.