JSCODE Logo
프로그래밍 과외블로그후기멘토진
회사명 : JSCODE대표 : 박재성사업자 등록번호 : 244-22-01557통신판매업 : 제 2023-인천미추홀-0381 호
학원 명칭 : 제이에스코드(JSCODE)원격학원학원설립ㆍ운영 등록번호 : 제6063호

서울특별시 구로구 경인로 20가길 11(오류동, 아델리아)

Copyright ⓒ 2025 JSCODE - 최상위 현업 개발자들의 프로그래밍 교육 All rights reserved.

이용약관개인정보처리방침
← 블로그 목록으로 돌아가기

Spring Boot 프로젝트에 Redis 셋팅 추가하기

JSCODE 박재성
JSCODE 박재성
2025-12-06
author
JSCODE 박재성
category
Redis
createdAt
Dec 6, 2025
series
비전공자도 이해할 수 있는 Redis 입문/실전
slug
add-redis-to-spring-boot
type
post
updatedAt
Dec 6, 2025 04:33 AM

✅ Spring Boot 프로젝트에 Redis 셋팅 추가하기

  1. Redis 의존성 추가하기
    1. build.gradle
      ... dependencies { ... implementation 'org.springframework.boot:spring-boot-starter-data-redis' }
       
      IDE : IntelliJ
      IDE : IntelliJ
      의존성을 새로 추가해준 뒤에 반드시 위 버튼을 눌러주어야 반영이 된다.
       
  1. application.yml 수정하기
    1. application.yml
      # 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 사용에 대한 로그가 조회되도록 설정
       
  1. Redis 설정 추가하기
    1. config/RedisConfig
      @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)); } }
config/RedisCacheConfig
@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(); } }
 
  1. BoardService에 캐싱 로직 추가하기
    1. BoardService
      @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 값을 레디스에 저장한다.
      notion image
      notion image
      (복습 :
      📖
      데이터를 캐싱할 때 사용하는 전략 (Cache Aside, Write Around)
      )
       
      [속성 값 설명]
      • cacheNames : 캐시 이름을 설정
      • key : Redis에 저장할 Key의 이름을 설정
        • 📖
          Redis에서 Key 네이밍 컨벤션 익히기
      • cacheManager : 사용할 cacheManager의 Bean 이름을 지정
       
 

✅ 테스트 해보기

  1. Spring Boot 서버를 실행시켜서 API 실행시켜보기
    1. notion image
      notion image
      Cache가 존재하지 않아서 DB로부터 데이터를 조회한 뒤 Cache를 생성했다고 로그가 찍혀있다.
       
      notion image
      한 번 더 새로고침을 해보면 Cache가 생성(Creating)되지 않고 기존 Cache를 조회해왔음을 알 수 있다.
       
  1. Redis-cli를 활용해 정상적으로 캐싱이 됐는 지 확인하기
    1. $ redis-cli $ keys * # Redis에 저장되어 있는 모든 key 조회 $ get getBoards::boards:page:1:size:10 # 특정 key의 Value 조회 $ ttl getBoards::boards:page:1:size:10 # 특정 key의 TTL 조회
 
author
category
Redis
createdAt
series
비전공자도 이해할 수 있는 Redis 입문/실전
slug
type
series-footer
updatedAt
Dec 6, 2025 04:33 AM
📎
이 글은 비전공자도 이해할 수 있는 Redis 입문/실전 (조회 성능 최적화편) 강의의 수업 자료 중 일부입니다.