我有一个 Spring Boot 应用程序,我试图在没有任何外部提供程序(redis 等)的情况下实现一个简单的缓存。
我只想缓存函数的响应
getFromDatabase
,但每次运行该函数时,打印行仍然会被执行,这表明缓存不起作用。
但是,如果我将
@Cacheable
注释放在 @PostMapping
本身上,那么缓存就可以工作。我的主课有以下内容
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
我的控制器有以下内容
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller {
@PostMapping("/temp")
public String retrieve() {
return getFromDatabase("yes");
}
@Cacheable(value = "databaseCache", key = "#key")
public String getFromDatabase(String key) {
System.out.println("Retrieving from database");
return "Fake";
}
}
Spring 不会为类中的所有方法创建代理。它仅考虑具有特定注释的方法。这就是为什么
@Cacheable
注释与 @PostMapping
一起使用,并在您提供的示例中被忽略。
我建议您将
getFromDatabase
方法移至单独的 @Service
类中来解决此问题。
@SpringBootApplication
@EnableCaching
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
控制器
@org.springframework.web.bind.annotation.RestController
public class Controller {
@Autowired
Service service;
@PostMapping("/temp")
public String retrieve() {
return service.getFromDatabase("yes");
}
}
服务
@org.springframework.stereotype.Service
public class Service {
@Cacheable(value = "databaseCache", key = "#key")
public String getFromDatabase(String key) {
System.out.println("Retrieving from database");
return "Fake";
}
}