为什么要用springcache?它解决了什么问题?
springcache 是spring3.1版本发布出来的,他是对使用缓存进行封装和抽象,通过在方法上使用annotation注解就能拿到缓存结果。正时因为用来annotation,所以它解决了业务代码和缓存代码的耦合度问题,即再不侵入业务代码的基础上让现有代码即刻支持缓存,它让开发人员无感知的使用了缓存。
特别注意:(注意:对于redis的缓存,springcache只支持string)
使用步骤:
-
pom文件加入依赖包
-
<!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!--spring cache--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!--spring cache连接池依赖包--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency>
-
-
配置文件加入redis配置信息
-
#redis配置 spring: redis: database: 0 host: 192.168.2.256 port: 6379 password: lettuce: pool: #连接池最大连接数 max-active: 8 #连接池中最大阻塞等待时间 max-wait: -1ms #连接池中的最大空闲连接 max-idle: 8 #连接池中的最小空闲连接 min-idle: 0 #连接超时时间 timeout: 5000ms
-
-
开启缓存配置,设置序列化
-
常用注解
@CacheConfig
@CacheConfig是类级别的注解,统一该类的所有缓存可以前缀
例:@CacheConfig(cacheNames={"user"})
public class UserService{ ....}
以上代码,代表了该类的所有缓存可以都是“user::”为前缀
@Cacheable
@Cacheable是方法级别的注解,用于将方法的结果缓存起来
例:@Cacheable(key="#id")
public User findUserById(Integer id){....}
以上方法被调用时,先从缓存中读取数据,如果缓存没有找到数据,再执行方法体,最后把返回值添加到缓存中
注意:@Cacheable 一般是配合@CacheConfig一起使用的
例如:上文的@CacheConfig(cacheNames={"user"})和@Cacheable({key="#id"})一起使用时,调用方法传入id=100,那redis对应的key=user::100,value通过采用GenericJackson2JsonRedisSerializer序列化为json
@CahcePut
@CahcePut是方法级别的注解,用于更新缓存
例:@CachePut(key="#obj.id")
public User updateUser(User obj){
this.UserMapper.UpdateByPrimarySelective(obj);
return this.userMapper.selectByPrimaryKey(obj.getId());
}
以上方法被调用时,先执行方法体,然后springcache通过返回更新缓存,即key="#obj.id",value=User
@CacheEvict(key="#id")
@CachePut是方法级别的注解,用于删除缓存
springcache的大坑
- 对于redis的缓存,springcache只支持String,其他的Hash、List、set、ZSet都不支持,所以对于Hash、List、set、ZSet只能用RedisTemplate
- 对于多表查询的数据缓存,springcache是用支持的,只支持单表的简单缓存。对于多表的整体缓存,只能用RedisTemplate。