【发布时间】:2020-04-05 08:26:51
【问题描述】:
我想使用一种机制来创建一次性计算函数。我尝试使用 Spring 缓存。但它不起作用。请帮我解决这个问题。我的代码如下,
Gradle 依赖
compile 'org.springframework.boot:spring-boot-starter-cache'
Spring Boot 应用主类
@SpringBootApplication
@EnableCaching
public class Application {
public static ApplicationContext applicationContext;
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// todo: Try to save response text and request body
applicationContext = SpringApplication.run(Application.class, args);
}
@Bean
WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/**")
.addResourceLocations("classpath:/")
.setCacheControl(CacheControl.maxAge(3600, TimeUnit.SECONDS).noTransform().mustRevalidate());
}
};
}
}
我的计算属性和测试方法
public String test(){
return hello();
}
@Cacheable("hello")
public String hello(){
System.out.println("hello");
return "Hello";
}
【问题讨论】:
-
究竟是什么不起作用?
-
第一次调用 'hello' 方法时。我希望它的结果添加到缓存中。再次调用'hello'方法后,无法调用,使用缓存返回结果。但我的代码 hello 方法再次调用。我用 SOUT 测量它。第二次呼叫。
-
我的英语不流利。对此我深表歉意。
标签: java spring spring-boot spring-cache