配置 Spring Cache 的缓存声明
在配置您的 Spring 应用程序并启用缓存之后,下一步是确定需要缓存的方法及其各自的策略。
您可以使用以下方法将缓存行为绑定到 Spring Cache 中的方法:
- 缓存注释
- 基于 XML 的声明式缓存
使用 Spring Caches 注解进行配置
对于缓存声明,抽象提供了 Java 注释,允许方法触发 Spring 缓存填充或驱逐。
例如:
让我们考虑一个具有两个类的 Web 服务,这两个类解释了如何使用 Spring 缓存进行缓存 @可缓存 注解。
// BookController.java
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
BookService booksService;
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
sdf.setLenient(true);
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
}
@RequestMapping(value="/bookstore", method = RequestMethod.GET)
public ModelAndView homePage(Model model) {
model.addAttribute("availableBooks", booksService.listAll());
return new ModelAndView("bookstore");
}
@RequestMapping(value = "/bookstore/new", method = RequestMethod.GET)
public String add(ModelMap model) {
model.addAttribute("book", new Book());
return "newBook";
}
@RequestMapping(value = "/bookstore/save", method = RequestMethod.POST)
public String saveBook(@ModelAttribute("book") Book book, BindingResult result) {
if (result.hasErrors()) {
return "newBook";
}
booksService.save(book);
return "redirect:/bookstore";
}
@RequestMapping(value = "/bookstore/edit", method = RequestMethod.GET)
public String showEditBookPage(@RequestParam int id, ModelMap model) {
Book book = booksService.get(id);
model.put("book", book);
return "newBook";
}
@RequestMapping(value = "/bookstore/edit", method = RequestMethod.POST)
public String updateBook(@ModelAttribute("book") Book book, BindingResult result) {
if (result.hasErrors()) {
return "newBook";
}
booksService.update(book);
return "redirect:/bookstore";
}
@RequestMapping(value = "/bookstore/delete")
public String deleteBook(@RequestParam int id) {
booksService.delete(id);
return "redirect:/bookstore";
}
@RequestMapping(value="/bookstore", method = RequestMethod.POST)
public ModelAndView findBook(ModelMap model, @RequestParam long isbn) {
Book book = booksService.findBookByIsbn(isbn);
if (book == null) {
return returnError(model, isbn);
}
model.put("book", book);
return new ModelAndView("bookdetails");
}
private ModelAndView returnError(ModelMap model, long isbn) {
String errorMessage = "The book with ISBN: " + isbn + " is not available.";
model.put("errorMessage", errorMessage);
return new ModelAndView(new RedirectView("bookstore"));
}
}
// BookService.java
@Service
class BookService {
@Autowired
private BookRepository repo;
public List<Book> listAll() {
return repo.findAll();
}
@CachePut(value = "books", key = "#book.getISBN()")
public void save(Book book) {
repo.save(book);
}
@CachePut(value = "books", key = "#book.getISBN()")
public void update(Book book) { repo.save(book); }
@Cacheable(value = "books", key = "#id")
public Book get(int id) {
return repo.findById(id);
}
@Cacheable(value = "books", key = "#isbn")
public Book findBookByIsbn(long isbn) {
return repo.findBookByIsbn(isbn);
}
@CacheEvict(value = "books", allEntries = true)
public void delete(int id) {
repo.deleteById(id);
}
}
要详细了解并了解有关其他缓存注释或自定义密钥生成器的创建的更多信息,请参阅 弹簧文档.
使用基于 XML 的声明式缓存进行配置
如果注释不是一个选项,即,如果您对源的访问权限有限或没有外部代码,则可以使用 XML 进行声明性缓存。 在这里,您可以在外部指定目标方法和缓存指令。
在下面的配置中, 图书服务 被设为可缓存。 缓存语义封装在 cache:advice
定义,它指示方法 查找图书按 Isbn 在处理时将数据放入缓存中 演示缓存.
备注
使用时 class
标签请确保您使用班级的完全限定名称。
<!-- the service we want to make cacheable -->
<bean id="bookService" class="com.spring.service.BookService"/>
<!-- cache definitions -->
<cache:advice id="booksCacheAdvice" cache-manager="cacheManager">
<cache:caching cache="demoCache">
<cache:cacheable method="findBookByIsbn" key="#isbn"/>
</cache:caching>
</cache:advice>
<app:config>
<app:advisor advice-ref="booksCacheAdvice" pointcut="execution(* com.spring.service.BookService.*(..))"/>
</app:config>
此外,为了使用自定义密钥生成器通过基于 XML 的缓存生成缓存密钥,需要定义为密钥生成器创建的 Bean,如下所示 CustomerKeyGenerator
作为一个班级。
<bean id="customerKeyGenerator" class="cachekeygenerator.CustomerKeyGenerator">
在这里, customerKeyGenerator
每当客户添加到时都会生成一个缓存密钥 客户缓存。 要使用此生成器,您必须指定 keygenerator
豆在你 cache:advice
标签。
<cache:advice id="customerCacheAdvice" key-generator="customerKeyGenerator">
<cache:caching cache="customersCache">
<cache:cacheable method="findCustomerByID"/>
</cache:caching>
</cache:advice>
修改所有这些配置后,您的应用程序现在就可以使用了 NCache 作为 Spring 缓存提供者。