从3.1开始,Spring引入了对Cache的支持。其使用方法和原理都类似于Spring对事务管理的支持。Spring Cache是作用在方法上的
使用Spring Cache的时候我们要保证我们缓存的方法对于相同的方法参数要有相同的返回结果。
使用Spring Cache需要我们做两方面的事:
1. 声明某些方法使用缓存
2. 配置Spring对Cache的支持
和Spring对事务管理的支持一样,Spring对Cache的支持也有基于注解和基于XML配置两种方式。
@EnableCaching 开启注解缓存
@Cacheable
可以标记在一个方法上,也可以标记在一个类上。
当标记在一个方法上时表示该方法是支持缓存的,当标记在一个类上时则表示该类所有的方法都是支持缓存的。
@Cacheable可以指定三个属性,value、key和condition。
参数
解释
example
value
缓存的名称,在 spring 配置文件中定义,必须指定至少一个
例如:
@Cacheable(value=”mycache”)
@Cacheable(value={”cache1”,”cache2”}
key
缓存的 key,可以为空,如果指定要按照 Spring的·EL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合
@Cacheable(value=”testcache”,key=”#userName”)
condition
缓存的条件,可以为空,使用 Spring的EL 编写,返回 true 或者 false,只有为 true 才进行缓存
@Cacheable(value=”testcache”,condition=”#userName.length()>2”)
@CachePut
@Cacheable标注的方法,Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行并将返回结果存入指定的缓存中。
@CachePut也可以声明一个方法支持缓存功能。与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
@CacheEvict
@CacheEvict是用来标注在需要清除缓存元素的方法或类上的。当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作。
@CacheEvict可以指定的属性有value、key、condition、allEntries和beforeInvocation。其中value、key和condition的语义与@Cacheable对应的属性类似。即value表示清除操作是发生在哪些Cache上的(对应Cache的名称);key表示需要清除的是哪个key,如未指定则会使用默认策略生成的key;condition表示清除操作发生的条件
allEntries属性
allEntries是boolean类型,表示是否需要清除缓存中的所有元素。
beforeInvocation属性
清除操作默认是在对应方法成功执行之后触发的,即方法如果因为抛出异常而未能成功返回时也不会触发清除操作。使用beforeInvocation可以改变触发清除操作的时间,当我们指定该属性值为true时,Spring会在调用该方法之前清除缓存中的指定元素。
项目结构(spring boot+mybatis plus)

依赖加载
-
-
-
org.springframework.boot -
spring-boot-starter-web -
-
-
-
org.projectlombok -
lombok -
true -
-
-
org.springframework.boot -
spring-boot-starter-test -
test -
-
-
org.springframework.boot -
spring-boot-starter-data-redis -
-
-
org.apache.commons -
commons-pool2 -
2.11.1 -
-
-
redis.clients -
jedis -
-
-
com.mysql -
mysql-connector-j -
-
-
com.baomidou -
mybatis-plus-boot-starter -
3.5.3 -
-
-
com.baomidou -
mybatis-plus-generator -
3.5.3 -
-
-
org.apache.velocity -
velocity-engine-core -
2.3 -
-
-
-
org.freemarker -
freemarker -
-
-
-
-
-
-
org.springframework.boot -
spring-boot-maven-plugin -
-
-
-
org.projectlombok -
lombok -
-
-
-
-
-
spring boot配置文件(.yml)
- spring:
- redis:
- host: 192.168.253.16
- database: 0
- password: root
- port: 6379
- lettuce:
- pool:
- max-active: 20
- max-wait: -1
- max-idle: 5
- min-idle: 0
- timeout: 1800000
- datasource:
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql:///prac?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
- username: root
- password: root
-
- jackson:
- date-format: yyyy-MM-dd HH:mm:ss
- time-zone: GMT+8
- serialization:
- write-date-keys-as-timestamps: false
-
- mybatis-plus:
- configuration:
- map-underscore-to-camel-case: true
- log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
- mapper-locations: classpath:/mapper/*.xml
- #逻辑删除 删除之前的值是0 之后是1
- global-config:
- db-config:
- logic-not-delete-value: 1
- logic-delete-value: 0
- type-aliases-package: com.tes.entity
service

redis缓存数据
