【百战商城】学习笔记2.3_SpringCache

72 阅读1分钟

springcache

1、创建一个demo演示 引入依赖为java web 和 redis

遇到的问题:(1)版本过高 需要降版本(搞死我!)

image-20230203144833430

修改地方 3.0.1 -》 2.7.6

image-20230203145200138

(2)开发环境jdk版本与本机环境版本不一致

需要改project-structure 和 setting 中的java complier

链接本地redis数据库(但其实默认是本机,后面用虚拟机的话就要配置这里)

image-20230203150819786

2、springcache注解 @Cacheable 用于方法

解释为当 针对方法中属性值(属性值为redis支持的8大类型),首先查找redis缓存,如果命中则不用走方法

@Cacheable有两个参数

  • cacheNames 前缀名称
  • key 后半部分内容,如果key的取值为 字符串 要使用单引号包含,key的取值为 Sepl

还需要在启动类上加上 @EnableCaching

3、demo

service

 package com.wing.springcache.service;
 ​
 public interface demoservice {
     String demo();
 }

impl

 package com.wing.springcache.service.demoimpl;
 ​
 import com.wing.springcache.service.demoservice;
 import org.springframework.cache.annotation.Cacheable;
 import org.springframework.stereotype.Service;
 ​
 @Service
 public class demoserviceImpl implements demoservice {
 ​
     @Cacheable(cacheNames = "com.wing",key = "'name'")
     @Override
     public String demo() {
         System.out.println("执行了方法demo");
         String name = "wing";
         return name;
     }
 }

controller

 package com.wing.springcache;
 ​
 import com.wing.springcache.service.demoimpl.demoserviceImpl;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 ​
 @RestController
 public class controller {
 ​
     @Autowired
     private demoserviceImpl demoservice;
 ​
     @RequestMapping("/")
     public String demo1(){
         return demoservice.demo();
     }
 }
 ​

刷新两次页面结果

image-20230203150612351

只显示一次demo

redis数据库

image-20230203150640161