Skip to content
On this page

为什么需要缓存

  • 对于数据库改动很少的数据,高频次的调用,会徒增数据库的压力。
  • 从缓存中获取数据,比直接访问数据库获取要快很多。
  • 直接访问一个已经存在的对象,要比从数据创建一个对象快。
  • 缓存的架构发展很迅速,从本地缓存 到 集群缓存 再到 分布式缓存(数据网格)。
  • 分布式系统一般会有一级缓存、二级缓存、要求更高些的会有三级缓存。
  • 但要用好缓存并不是那么简单,我们还需要具有缓存穿透、缓存雪崩对应的解决方案。
  • 本章只讲述 Spring 下使用缓存的方法,后续运维工程师可根据系统的实际业务情况来采用不同的缓存架构。

小提示

我们可以使用 Redis 可视化工具Another Redis Desktop Manager来实时查看redis的使用情况

代码示例

添加读取缓存

java
@Slf4j
@RestController
@RequestMapping("/api")
public class DemoController {

   @GetMapping("/info")
   @Cacheable(cacheNames = "demo-info", key = "#info")
   public R<String> info(String info) {
      log.info("本条信息没有从缓存获取");
      return "Hello,Response success:" + info;
   }

}

移除缓存

java
@Slf4j
@RestController
@RequestMapping("/api")
public class DemoController {

   @GetMapping("/info")
   @Cacheable(cacheNames = "demo-info", key = "#info")
   public R<String> info(String info) {
      log.info("本条信息没有从缓存获取");
      return R.data("Hello,Response success:" + info);
   }

   @GetMapping("/remove-info")
   @CacheEvict(cacheNames = "demo-info", key = "#info")
   public R<String> removeInfo(String info) {
      return R.success("删除缓存成功");
   }

}

结尾语

好了,简单的缓存概念及其使用已经讲解完毕,更深一层的,我们可以查阅 Spring 的官方文档进行深入学习。 官方文档直达:https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache