Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✏️ Fix: 캐시 키 변경 & 커스텀 캐시 Evict 로직 구현 #143

Merged
merged 1 commit into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/main/java/briefing/briefing/api/BriefingV2Api.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class BriefingV2Api {

@GetMapping("/briefings")
@Operation(summary = "03-01Briefing \uD83D\uDCF0 브리핑 목록 조회 V2", description = "")
@Cacheable(value = "findBriefingsV2", key = "#params.toString()")
@Cacheable(value = "findBriefingsV2", key = "#params.getType()")
public CommonResponse<BriefingResponseDTO.BriefingPreviewListDTOV2> findBriefingsV2(
@ParameterObject @ModelAttribute BriefingRequestParam.BriefingPreviewListParam params) {
List<Briefing> briefingList = briefingQueryService.findBriefings(params, APIVersion.V2);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package briefing.common.aop.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CacheEvictByBriefingId {
String value(); // 캐시 이름

String briefingId(); // 캐시 키를 위한 briefingId
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package briefing.common.aop.aspect;

import java.util.Optional;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

import briefing.briefing.domain.Briefing;
import briefing.briefing.domain.repository.BriefingRepository;
import briefing.common.aop.annotation.CacheEvictByBriefingId;
import lombok.RequiredArgsConstructor;

@Aspect
@Component
@RequiredArgsConstructor
public class CacheEvictByBriefingIdAspect {

private final BriefingRepository briefingRepository;
private final CacheManager cacheManager;
private SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
private StandardEvaluationContext evaluationContext = new StandardEvaluationContext();

@After(value = "@annotation(cacheEvictByBriefingId)")
public void evictCache(JoinPoint joinPoint, CacheEvictByBriefingId cacheEvictByBriefingId) {
System.out.println("AOP CALL!!!");

String briefingIdExpression = cacheEvictByBriefingId.briefingId();
Long briefingId = evaluateExpression(joinPoint, briefingIdExpression, Long.class);

Optional<Briefing> optionalBriefing = briefingRepository.findById(briefingId);

if (optionalBriefing.isPresent()) {
Briefing briefing = optionalBriefing.get();
String cacheKey = briefing.getType().name();
Cache cache = cacheManager.getCache(cacheEvictByBriefingId.value());
System.out.println(cacheEvictByBriefingId.value());
System.out.println(cacheKey);
System.out.println(cache);
if (cache != null) {
cache.evict(cacheKey);
}
}
}

private <T> T evaluateExpression(
JoinPoint joinPoint, String expression, Class<T> desiredResultType) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Object[] args = joinPoint.getArgs();
String[] parameterNames = methodSignature.getParameterNames();

for (int i = 0; i < parameterNames.length; i++) {
evaluationContext.setVariable(parameterNames[i], args[i]);
}

Expression parsedExpression = spelExpressionParser.parseExpression(expression);
return parsedExpression.getValue(evaluationContext, desiredResultType);
}
}
6 changes: 3 additions & 3 deletions src/main/java/briefing/scrap/api/ScrapV2Api.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

import java.util.List;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import briefing.common.aop.annotation.CacheEvictByBriefingId;
import briefing.common.response.CommonResponse;
import briefing.scrap.application.ScrapCommandService;
import briefing.scrap.application.ScrapQueryService;
Expand All @@ -23,7 +23,7 @@ public class ScrapV2Api {
private final ScrapQueryService scrapQueryService;
private final ScrapCommandService scrapCommandService;

@CacheEvict(value = "findBriefingsV2", allEntries = true)
@CacheEvictByBriefingId(value = "findBriefingsV2", briefingId = "#request.getBriefingId()")
@Operation(summary = "05-01 Scrap📁 스크랩하기 V2", description = "브리핑을 스크랩하는 API입니다.")
@PostMapping("/scraps/briefings")
public CommonResponse<ScrapResponse.CreateDTOV2> createV2(
Expand All @@ -33,7 +33,7 @@ public CommonResponse<ScrapResponse.CreateDTOV2> createV2(
return CommonResponse.onSuccess(ScrapConverter.toCreateDTOV2(createdScrap, scrapCount));
}

@CacheEvict(value = "findBriefingsV2", allEntries = true)
@CacheEvictByBriefingId(value = "findBriefingsV2", briefingId = "#briefingId")
@Operation(summary = "05-02 Scrap📁 스크랩 취소 V2", description = "스크랩을 취소하는 API입니다.")
@DeleteMapping("/scraps/briefings/{briefingId}/members/{memberId}")
public CommonResponse<ScrapResponse.DeleteDTOV2> deleteV2(
Expand Down
Loading