如果没有引入其他缓存依赖时,springboot默认使用ConcurrenMapCacheManager作为缓存管理器
本文介绍使用redis缓存
引入依赖
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
|
配置
1 2 3 4 5 6 7 8 9 10 11 12
| spring: redis: host: localhost port: 6379 database: 0 password: cache: type: redis
|
开启缓存
1 2 3 4 5 6 7 8
| @EnableCaching @SpringBootApplication public class MyApplication {
public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
|
缓存
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| @Service public class TestService {
@Cacheable(value = "cache-test", key = "#p0") public String getName(long id){ System.out.println("等待3秒。。。。"); try { Thread.sleep(3000L); } catch (InterruptedException e) { e.printStackTrace(); } return id + ":name"; }
@CachePut(value = "cache-test", key = "#p0") public String updateName(long id){ System.out.println("更新名称"); return id + ":nickname"; }
@CacheEvict(value = "cache-test", key = "#p0") public void deleteName(long id){ System.out.println("删除名称"); } }
|
@Cacheable:获取缓存
value:缓存名称,必须有,spring根据value进行分组
key: 缓存的key,支持spel表达式,如果没有则按照方法的所有参数进行组合
@CachePut:更新缓存
value和key与@Cacheabl的value和key相同
@CacheEvict:删除缓存
value和key与@Cacheabl的value和key相同