注:springcache并非springboot特有的功能
? ?
? ?
一、创建项目并导入依赖
? ?
? ?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
? ?
? ?
Springboot2.1.5之后版本远程连接redis时必须要加入spring-security依赖
? ?
二、相关配置和代码
? ?
Application.properites
? ?
spring.redis.host=192.168.21.134
spring.redis.port=6379
spring.redis.database=0
spring.redis.password=520hufei520
? ?
? ?
spring.cache.cache-names=c1
? ?
? ?
spring.cache.cache-names=c1,c2…. 表示启动时创建缓存名称,用逗号分隔表示多个缓存名
? ?
? ?
创建pojo、service用来测试
? ?
注:使用缓存需要在springboot启动类加上
@EnableCaching以用来开启缓存
? ?
? ?
? ?
当方法只有一个参数时,默认缓存的key是id
? ?
当方法有两个参数时,就需要指定key
? ?
? ?
? ?
#id | 属性名 |
#methodName | 函数名 |
#method.name | 同上 |
#caches | 使用缓存集合中作为key,例子#caches[0] |
#args | 使用参数名作为key,使用方法同上 |
#target | 当前调用对象作为key |
#target.class | 当前作用对象的class |
? ?
还可以自己定义key
? ?
? ?
这也是一种写法
? ?
? ?
@CacheEvict
删除的同步缓存
? ?
@CachePut
? ?
? ?
修改时的同步缓存
? ?
? ?
在每个方法都定义一个缓存名似乎也很麻烦,可以其中定义在类上
? ?
? ?
? ?
? ?
? ?
? ?
? ?
? ?
? ?
? ?
? ?
? ?
原文:https://www.cnblogs.com/fernfei/p/12174174.html