... dependencies { ... implementation 'org.springframework.boot:spring-boot-starter-data-redis' }

# local 환경 spring: profiles: default: local datasource: url: jdbc:mysql://localhost:3306/mydb username: root password: password driver-class-name: com.mysql.cj.jdbc.Driver jpa: hibernate: ddl-auto: update show-sql: true data: redis: host: localhost port: 6379 logging: level: org.springframework.cache: trace # Redis 사용에 대한 로그가 조회되도록 설정
@Configuration public class RedisConfig { @Value("${spring.data.redis.host}") private String host; @Value("${spring.data.redis.port}") private int port; @Bean public LettuceConnectionFactory redisConnectionFactory() { // Lettuce라는 라이브러리를 활용해 Redis 연결을 관리하는 객체를 생성하고 // Redis 서버에 대한 정보(host, port)를 설정한다. return new LettuceConnectionFactory(new RedisStandaloneConfiguration(host, port)); } }
@Configuration @EnableCaching // Spring Boot의 캐싱 설정을 활성화 public class RedisCacheConfig { @Bean public CacheManager boardCacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration .defaultCacheConfig() // Redis에 Key를 저장할 때 String으로 직렬화(변환)해서 저장 .serializeKeysWith( RedisSerializationContext.SerializationPair.fromSerializer( new StringRedisSerializer())) // Redis에 Value를 저장할 때 Json으로 직렬화(변환)해서 저장 .serializeValuesWith( RedisSerializationContext.SerializationPair.fromSerializer( new Jackson2JsonRedisSerializer<Object>(Object.class) ) ) // 데이터의 만료기간(TTL) 설정 .entryTtl(Duration.ofMinutes(1L)); return RedisCacheManager .RedisCacheManagerBuilder .fromConnectionFactory(redisConnectionFactory) .cacheDefaults(redisCacheConfiguration) .build(); } }
@Service public class BoardService { private BoardRepository boardRepository; private Pageable pageable; public BoardService(BoardRepository boardRepository) { this.boardRepository = boardRepository; } @Cacheable(cacheNames = "getBoards", key = "'boards:page:' + #page + ':size:' + #size", cacheManager = "boardCacheManager") public List<Board> getBoards(int page, int size) { Pageable pageable = PageRequest.of(page - 1, size); Page<Board> pageOfBoards = boardRepository.findAllByOrderByCreatedAtDesc(pageable); return pageOfBoards.getContent(); } }
@Cacheable 어노테이션을 붙이면 Cache Aside 전략으로 캐싱이 적용된다. 즉, 해당 메서드로 요청이 들어오면 레디스를 확인한 후에 데이터가 있다면 레디스의 데이터를 조회해서 바로 응답한다. 만약 데이터가 없다면 메서드 내부의 로직을 실행시킨 뒤에 return 값으로 응답한다. 그리고 그 return 값을 레디스에 저장한다. 

cacheNames : 캐시 이름을 설정key : Redis에 저장할 Key의 이름을 설정cacheManager : 사용할 cacheManager의 Bean 이름을 지정


$ redis-cli $ keys * # Redis에 저장되어 있는 모든 key 조회 $ get getBoards::boards:page:1:size:10 # 특정 key의 Value 조회 $ ttl getBoards::boards:page:1:size:10 # 특정 key의 TTL 조회