gpt4 book ai didi

Spring - 如何使用 aspectJ 缓存自调用?

转载 作者:行者123 更新时间:2023-12-05 01:11:33 25 4
gpt4 key购买 nike

感谢您点击我的问题。我想在自调用中调用缓存方法,所以需要使用AspectJ。(缓存的配置没问题)

  1. 添加 AspectJ 依赖项
implementation 'org.springframework.boot:spring-boot-starter-aop'
  1. 将 @EnableCaching(mode = AdviceMode.ASPECTJ) 添加到我的 application.java
@EnableJpaAuditing
@EnableCaching(mode = AdviceMode.ASPECTJ) // <-- here
@SpringBootApplication
public class DoctorAnswerApplication {

public static void main(String[] args) {
SpringApplication.run(DoctorAnswerApplication.class, args);
}

}
  1. 我的服务.java
@Service
public class PredictionService {

@Cacheable(value = "findCompletedRecordCache")
public HealthCheckupRecord getRecordComplete(Long memberId, String checkupDate) {
Optional<HealthCheckupRecord> recordCheckupData;
recordCheckupData = healthCheckupRecordRepository.findByMemberIdAndCheckupDateAndStep(memberId, checkupDate, RecordStep.COMPLETE);

return recordCheckupData.orElseThrow(NoSuchElementException::new);
}
}
  1. 我的测试代码
    @Test
public void getRecordCompleteCacheCreate() {
// given
Long memberId = (long)this.testUserId;
List<HealthCheckupRecord> recordDesc = healthCheckupRecordRepository.findByMemberIdAndStepOrderByCheckupDateDesc(testUserId, RecordStep.COMPLETE);
String checkupDate = recordDesc.get(0).getCheckupDate();
String checkupDate2 = recordDesc.get(1).getCheckupDate();

// when
HealthCheckupRecord first = predictionService.getRecordComplete(memberId,checkupDate);
HealthCheckupRecord second = predictionService.getRecordComplete(memberId,checkupDate);
HealthCheckupRecord third = predictionService.getRecordComplete(memberId,checkupDate2);

// then
assertThat(first).isEqualTo(second);
assertThat(first).isNotEqualTo(third);
}

我没有...?我没有开设任何与 aspectJ 相关的类(class)。我认为 @EnableCaching(mode = AdviceMode.ASPECTJ) 使 @Cacheable 由 AspectJ 代替 Spring AOP(proxy) 工作。

最佳答案

你读过 Javadoc for EnableCaching 了吗? ?

Note that if the mode() is set to AdviceMode.ASPECTJ, then the value of the proxyTargetClass() attribute will be ignored. Note also that in this case the spring-aspects module JAR must be present on the classpath, with compile-time weaving or load-time weaving applying the aspect to the affected classes. There is no proxy involved in such a scenario; local calls will be intercepted as well.

所以请检查你是否

  1. 在类路径上有 spring-aspects
  2. 使用参数 java -javaagent:/path/to/aspectjweaver.jar 启动您的应用程序。

#2 有一个替代方案,但使用 Java 代理是最简单的。我不是 Spring 用户,所以我不是 Spring 配置方面的专家,但即使像我这样的 Spring 菜鸟也成功使用了 Java 代理,所以请先试一试。

关于Spring - 如何使用 aspectJ 缓存自调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62932146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com