Spring-Cache快速入门

Spring cache依赖的添加,能帮助我们使用应用程序的内存缓存,可以避免每次查询都需要真正的去做查询,命中缓存时候能够马上换回值并更新缓存,官方doc原文如是说:

This example demonstrates the use of caching on a potentially costly operation. Before invoking computePiDecimal, the abstraction looks for an entry in the piDecimals cache that matches the i argument. If an entry is found, the content in the cache is immediately returned to the caller, and the method is not invoked. Otherwise, the method is invoked, and the cache is updated before returning the value.
更多详见:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-caching.html

在spring boot工程下搭建一个cache入门demo只需三板斧:

  • 引入依赖

            org.springframework.boot
            spring-boot-starter-cache
        
  • 开启缓存开关
@EnableCaching
@SpringBootApplication
public class SpringCacheDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringCacheDemoApplication.class, args);
    }
}
  • 在需要缓存的方法上设置缓存标记
 @Override
    @Cacheable("Zhoudy-Books")
    public Book getByIsbn(String isbn) {
        simulateSlowService();
        return new Book(isbn, "Some book");
    }

附上根据官网的示例写的示意代码:

https://gitee.com/danni505/Spring-cache/tree/master

你可能感兴趣的:(Spring-Cache快速入门)