데이터나 값을 미리 복사해 놓는 임시 저장소를 가리킨다. 이러한 cache는 접근 시간에 비해 원래 데이터를 접근하는 시간이 오래 걸리는 경우나 값을 다시 계산하는 시간을 절약하고 싶은 경우에 사용한다. cache에 데이터를 미리 복사해 놓으면 계산이나 접근 시간 없이 더 빠른 속도로 데이터에 접근 가능하다.
정리하면 디스크에 접근하여 정보를 얻어오는 것 보다 빠른 속도로 데이터 조회가 가능하다. 하지만 인메모리로 설정할 경우 휘발성이기 때문에 서버가 다운되면 데이터는 사라질 수 있다. 즉 영구적으로 보관하기 위한 용도가 아니다.
만약 메인 페이지에 랭킹과 관련된 데이터를 매번 조회한다고 가정하면 해당 웹 서비스에 접속할 때 마다 랭킹 정보들을 데이터베이스에서 조회할 것이다. 이러한 상황은 클라이언트가 갑작스럽게 몰리게 되면 큰 부담으로 다가온다.
이때 이렇게 자주 조회되는 데이터를 cache에 보관하는 것이다. cache에 보관된 데이터는 일정 시간(유효기간 TTL)을 가지고 유지된다. 해당 기간이 종료되면 cache를 삭제하게 된다.
cache는 자주 조회되는 랭킹, 쇼핑몰의 베스트셀러, 추천 상품 등의 데이터를 보관하는데 용이하다. 단순히 관련 요청이 들어오면 데이터베이스에 접근하여 다시 조회하기 보단 cache에 저장된 기존에 조회한 데이터를 사용하면 되기 때문이다.
Spring에서는 framework 레벨에서 이러한 cache를 추상화하여 지원해준다. 또한 Redis, EhCache 등 bean 설정을 통해 빠르게 cache 저장소로 추가할 수 있다.
필자는 그중 redis를 활용한 적용 예제를 간단히 사용해보려 한다.
build.gradle
plugins {
id 'org.springframework.boot' version '2.5.4'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'me.hyeonic'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
redis로 cache를 구현하기 위해 spring-data-redis
를 추가하였다. 그 밖에도 간단한 예제 생성을 위해 web
, spring-data-jpa
, h2
database의 의존성을 추가하였다.
application.yml
spring:
h2:
console:
enabled: true
datasource:
hikari:
jdbc-url: jdbc:h2:mem:testdb;MODE=MYSQL
username: sa
jpa:
hibernate:
ddl-auto: create-drop
properties:
hibernate:
show_sql: false
format_sql: true
dialect: org.hibernate.dialect.MySQL57Dialect
storage_engine: innodb
defer-datasource-initialization: true
cache:
type: redis
redis:
host: localhost
port: 6379
logging.level:
org.hibernate.SQL: debug
com.skhuedin.skhuedin: debug≠
RedisConfig.java
@EnableRedisRepositories
@Configuration
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(host, port);
return new LettuceConnectionFactory(redisStandaloneConfiguration);
}
}
redis 연결을 위해 RedisConnectionFactory를 @Bean
을 활용하여 등록하였다. redis는 local 환경에 설치한 후 사용하였다.
CacheConfig.java