springboot缓存

361 阅读2分钟

如果没有引入其他缓存依赖时,springboot默认使用ConcurrenMapCacheManager作为缓存管理器
本文介绍使用redis缓存

支持的缓存类型

  • Generic
  • JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, and others)
  • EhCache 2.x
  • Hazelcast
  • Infinispan
  • Couchbase
  • Redis
  • Caffeine
  • Simple 也可以自己实现CacheManager

1.引入依赖

<!-- 缓存依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- redis依赖,不引入则默认使用ConcurrenMapCacheManager -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.修改配置文件

spring:
redis:
#地址
host: localhost
#端口
port: 6379
#索引库
database: 1
#密码
password:
#超时时间
timeout: 5000ms
cache:
#设置缓存类型
type: redis
redis:
#缓存存活时间,不设置则没有过期时间
time-to-live: 1800000ms

3.开启缓存

@SpringBootApplication
//开启缓存
@EnableCaching
public class CacheApplication {

public static void main(String[] args) {
SpringApplication.run(CacheApplication.class, args);
}

}

4.service

@Service
public class CacheService {

/**
* 如果缓存中有则直接走缓存,如果没有则执行方法,将方法的返回值作为缓存
* @param id
* @return
*/

@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";
}

/**
* 将方法的返回值更新到缓存
* @param id
* @return
*/

@CachePut(value = "cache-test", key = "#p0")
public String updateName(long id){
System.out.println("更新名称");
return id + ":nickname";
}

/**
* 删除缓存
* @param id
*/

//allEntries:方法执行完之后将缓存名称为cache-test的所有缓存删除
//@CacheEvict(value = "cache-test", allEntries = true)
@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相同

5.测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class CacheApplicationTests {
@Autowired
private CacheService cacheService;

@Test
public void contextLoads() {
System.out.println(cacheService.getName(1L));
System.out.println(cacheService.getName(1L));
cacheService.updateName(1L);
System.out.println(cacheService.getName(1L));
cacheService.deleteName(1L);
System.out.println(cacheService.getName(1L));
}

}

控制台输出:

等待3秒。。。。
1:name
1:name
更新名称
1:nickname
删除名称
等待3秒。。。。
1:name\

第一次获取name时缓存中没有数据,则直接走方法并将返回值存储到缓存
第二次获取name时缓存中有数据,跳过方法直接从缓存中获取数据
更新缓存
第三次获取name时缓存中的数据修改成了1:nickname
删除缓存
第四次获取name时缓存中没有数据,走方法并将返回值存储到缓存

项目路径


作者博客

作者公众号 在这里插入图片描述