[Web] 스프링부트 Redis 사용법 - (적용편)

업데이트:



1. 어노테이션 이해

캐싱이 필요한 메서드에 아래의 어노테이션을 사용하게 됩니다.

각각을 어떻게 사용해야하는지 알아봅시다.


1) @Cacheable

: 지정한 key, value로 메서드의 결과 값을 redis에 ‘저장’합니다.

  • value : 캐시의 이름
  • key : 하위 구별자 (SpEL 표현식을 사용)
  • 예시)
    @Cacheable(value="Post", key="'Post#' + #postId")
    @GetMapping("/{postId}")
    public PostResponseDTO getPost(@PathVariable Long postId) {
          return postService.getPost(postId);
    }
    

    medis2) image


2) @CacheEvict

: 메서드 호출 후에 지정한 key, value에 해당하는 redis의 값을 ‘삭제’합니다.

  • value : 캐시의 이름
  • key : 하위 구별자 (SpEL 표현식을 사용)
  • allentries : 캐시 내부의 모든 항목을 제거할지 여부 (default : false)
  • 예시)
    @CacheEvict(value="Post", key="'Post#' + #postId")
    @DeleteMapping("/{postId}")
    public ResponseDTO deletePost(@PathVariable Long postId) {
      postService.deletePost(postId, account);
      return ResponseDTO.of(PostResponseCode.POST_DELETE_OK);
    }
    


3) @Caching

: 여러 개의 기능(cacheable, evict)을 사용할 수 있다.

  • cacheable : @Cacheable 정의하는 자리
  • evict : @CacheEvict 정의하는 자리
  • 예시)
    @Operation(summary = "공고 단건 삭제")
    @Caching(
      evict = {
          @CacheEvict(value="Post", key="'Post#' + #postId"),
          @CacheEvict(value="MainPosts", key="'MainPosts'")
      }
    )
    @DeleteMapping("/{postId}")
    public ResponseDTO deletePost(@PathVariable Long postId) {
      postService.deletePost(postId, account);
      return ResponseDTO.of(PostResponseCode.POST_DELETE_OK);
    }
    



2. 캐시 적용하기

캐시를 적용하기 이전에 어떤 곳에 캐시를 적용하는 것이 적합한지 알고 있어야 합니다.

수정이 자주 일어나는 리소스의 경우는 캐시를 적용하는 것이 적합하지 않을 수 있습니다.

왜냐하면 수정이 일어날 때마다 redis의 값들을 날려버리게 되고,

조회가 일어나면 캐시를 적용해두었으니 redis에서 key, value가 일치하는 값이 있는지 훑고,

redis에 값이 없다면 결과 값을 다시 redis에 값을 넣는 과정이 생기기 때문입니다.


끝~~~




카테고리:

업데이트: