【Spring Cache】

Spring Cache

Spring Cache介绍

Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注释,就能实现缓存功能。
Spring Cache提供了一层抽象,,底层可以切换不同的cache实现,具体就是通过CacheManager接口来统一不同的缓存技术
CacheManager是Spring提供的各种缓存技术抽象接口
针对不同缓存技术需要实现不同的CacheManager:

CacheManager描述
EhCacheCachManager使用EhCache作为缓存技术
GuavaCacheManager使用Google的GuavaCache作为缓存技术
RedisCacheManager使用Redis作为缓存技术

Spring Cache常用注解

注解说明
@EnableCaching开启缓存注解功能
@Cacheable在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
@CachePut将方法的返回值放到缓存中
@CacheEvict将一条或多条数据从缓存中删除

在spring boot 项目中,使用缓存技术只需在项目中导入相关缓存技术的依赖包,并在启动类上使用@EnableCaching开启缓存支持即可
例如:使用Redis作为缓存技术,只需要导入Spring data Redis的maven坐标即可。

Spring Cache使用方式

在Spring Boot项目中使用Spring Cache的操作步骤(使用redis缓存技术):
1,导入maven坐标
spring-boot-starter-data-redis、spring-boot-starter-cache
2,配置application.yml

spring
	redis:
      host:172.0.0.1
      port:6379
      password:root@123456
      database:0
	cache:
	  redis:
	  	time-to-live:1800000 #s设置缓存有效期

3,在启动类上加入@EnableCaching注解,开启缓存注解功能
4,在Controller的方法上加入@Cacheable、@CacheEvict等注解,进行缓存操作


版权声明:本文为oycxhi原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。