스프링 심화 TIL

캐싱 전략

쫑글이 2024. 8. 13. 12:13

 

    @CachePut(cacheNames = "itemCache", key = "args[0]")
    @CacheEvict(cacheNames = "itemAllCache", allEntries = true)
    public ItemDto update(Long id, ItemDto dto) {
        Item item = itemRepository.findById(id)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
        item.setName(dto.getName());
        item.setDescription(dto.getDescription());
        item.setPrice(dto.getPrice());
        return ItemDto.fromEntity(itemRepository.save(item));
    }

 

@CachePut : 메서드가 실행될 때마다 결과를 itemCache 캐시에 저장

@Cacheable과의 차이점 : @Cacheable은 캐시에 데이터가 없는 경우에만 메서드를 실행하고 캐시에 결과를 저장하는데(캐시 어사이드 방식) @CachePut은 메서드가 실행되면 결과가 항상 캐시에 저장된다.(캐시 프런트 방식)

 

@CacheEvict : update() 메서드가 실행될 때 마다 itemAllCache를 비워준다.