개요
Ehcache는 자바에서 많이 사용되는 인메모리 캐싱 솔루션으로, Spring Batch와 함께 사용하면 성능을 향상시킬 수 있습니다. 이번 포스트에서는 Ehcache와 Spring Batch를 연동하는 방법을 다루겠습니다.
의존성 추가
먼저, 프로젝트의 pom.xml
파일에 Ehcache와 Spring Batch의 의존성을 추가해야합니다. 아래의 의존성을 <dependencies>
태그 내에 추가해주세요.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
Ehcache 설정
Ehcache를 설정하는 방법은 여러 가지가 있지만, 가장 간단한 방법은 아래의 내용을 application.yml
또는 application.properties
파일에 추가하는 것입니다.
spring:
cache:
type: ehcache
위의 설정은 Spring Cache가 Ehcache를 사용하도록 지정하는 것입니다.
CacheManager 설정
다음으로, Ehcache를 사용하기 위한 CacheManager
빈을 설정해야합니다. @Configuration
어노테이션을 가진 클래스에 아래와 같은 빈을 추가해주세요.
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheManager().getObject());
}
@Bean
public EhCacheManagerFactoryBean ehCacheManager() {
EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean();
factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
factoryBean.setShared(true);
return factoryBean;
}
}
위의 코드는 Ehcache를 사용할 수 있는 CacheManager
빈을 등록하는 것입니다. ehcache.xml
파일은 필요에 따라 프로젝트에 추가해야합니다.
캐시 사용
이제 Ehcache를 사용하여 Spring Batch를 구성할 수 있습니다. 예를 들어, ItemReader
에서 데이터를 읽고, 읽은 데이터를 캐싱하고자 한다면, 아래와 같이 코드를 작성할 수 있습니다.
import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
@Component
public class CachingItemReader implements ItemReader<String> {
private final ItemReader<String> delegate;
@Autowired
public CachingItemReader(ItemReader<String> delegate) {
this.delegate = delegate;
}
@Cacheable("cacheName")
@Override
public String read() {
return delegate.read();
}
}
위의 코드는 @Cacheable
어노테이션을 사용하여 데이터를 캐싱하는 예시입니다. ItemReader
에 @Cacheable
어노테이션을 추가하면, 데이터를 읽을 때마다 캐시에 저장됩니다.
결론
이렇게 하면 Ehcache와 Spring Batch를 연동하는 방법에 대해 알아보았습니다. 캐싱을 통해 데이터 액세스 성능을 향상시킬 수 있으며, 다른 Spring 프레임워크와의 통합도 가능합니다. 더 자세한 내용은 Ehcache와 Spring Batch의 공식 문서를 참조해주세요.