我目前正在为生产中的一些方法实现Spring缓存.它与使用@GetMapping
的REST控制器方法一起工作得很好,该方法调用用@Cacheable
注释的服务方法.
然而,当我try 在Groovy脚本中实现相同的缓存机制时,它似乎不起作用.ChatGPT认为,这可能是因为服务中用@Cacheable
注释的方法调用发生在组件的构造函数中.
为了进一步研究,我创建了一个测试Spring Boot应用程序,并try 从用@PostConstruct
注释的另一个Bean的方法中调用一个@Cacheable
的测试方法,但不幸的是,它仍然不起作用.在阅读了几本手册和文档后,我怀疑没有创建代理或类似的东西.
以下是我的测试应用程序的代码:
package test.spring.springtest;
import jakarta.annotation.PostConstruct;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringTestApplication {
private final JavaStarter javaStarter;
public SpringTestApplication(JavaStarter javaStarter) {
this.javaStarter = javaStarter;
}
public static void main(String[] args) {
SpringApplication.run(SpringTestApplication.class, args);
}
@PostConstruct
public void invokeJavaStarterMethod() {
javaStarter.invokeTestMethod("test");
}
}
package test.spring.springtest.config;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("cache");
}
}
package test.spring.springtest;
import org.springframework.stereotype.Component;
import test.spring.springtest.service.JavaService;
@Component
public class JavaStarter {
private final JavaService javaService;
JavaStarter(JavaService javaService) {
this.javaService = javaService;
}
public void invokeTestMethod(String input) {
for (int i = 0; i < 3; i++) {
System.out.println("Output: " + javaService.testMethod(input));
System.out.println();
}
}
}
package test.spring.springtest.service;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class JavaService {
@Cacheable(cacheNames = "cache")
public String testMethod(String input) {
System.out.println("Cache is not being used");
return input;
}
}
您能解释一下为什么缓存行为没有像预期的那样工作吗?
在我的项目中,我决定在我的Spring Boot应用程序中使用@Cacheable
注释实现缓存.当我将其应用于调用用@Cacheable
注释的服务方法的REST控制器方法时,缓存工作得很好.
然而,当我试图在Groovy脚本中使用相同的缓存机制时,它没有达到预期的效果.我甚至try 用@PostConstruct
从另一个bean的方法调用一个测试方法,但这也没有解决问题.
我花时间研究了各种手册和文档以找到解决方案,但我找不到问题的根本原因.似乎存在缓存行为不能像预期的那样工作的原因.这可能与我如何使用@Cacheable
注释或它如何与其他组件交互有关.