作用
当项目业务量及数据量上升时,数据库压力会变大,数据访问速度会变慢,会出现页面加载数据时转圈圈的情况,影响用户体验,这时候缓存起到了作用,将访问过的数据存在redis中,再次访问此数据时可直接从redis中取出,大大提升效率。
应用
基于Springboot的应用
引入POM文件
<!-- redis缓存 -->
<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.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
配置类(策略器)
@Component
public class RedisConfig {
@Bean
public RedisTemplate<Object, Object> commonRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Object> ser = new Jackson2JsonRedisSerializer<Object>(Object.class);
template.setDefaultSerializer(ser);
return template;
}
@Bean
@Primary
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1));
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
}
开启注解
在启动类开启注解@EnableCaching
@SpringBootApplication
@MapperScan("com.purchasecloud.srm.dao")
@EnableDiscoveryClient //向注册中心注册
@EnableCaching
@EnableFeignClients
public class PurchasecloudSrmUserApplication {
public static void main(String[] args) {
SpringApplication.run(PurchasecloudSrmUserApplication.class, args);
}
}
抽取公共的缓存配置
作用在service上
@CacheConfig(cacheNames=ModuleName.SRM_USER) //抽取缓存的公共配置
缓存注解
查询时缓存注解
/**
* 运行流程:
* * @Cacheable:
* * 1、方法运行之前,先去查询Cache(缓存组件),按照cacheNames指定的名字获取;
* * (CacheManager先获取相应的缓存),第一次获取缓存如果没有Cache组件会自动创建。
* * 2、去Cache中查找缓存的内容,使用一个key,默认就是方法的参数;
* * key是按照某种策略生成的;默认是使用keyGenerator生成的,默认使用SimpleKeyGenerator生成key;
* * SimpleKeyGenerator生成key的默认策略;
* * 如果没有参数;key=new SimpleKey();
* * 如果有一个参数:key=参数的值
* * 如果有多个参数:key=new SimpleKey(params);
* * 3、没有查到缓存就调用目标方法;
* * 4、将目标方法返回的结果,放进缓存中
* *
* * @Cacheable标注的方法执行之前先来检查缓存中有没有这个数据,默认按照参数的值作为key去查询缓存,
* * 如果没有就运行方法并将结果放入缓存;以后再来调用就可以直接使用缓存中的数据;
* *
* * 核心:
* * 1)、使用CacheManager【ConcurrentMapCacheManager】按照名字得到Cache【ConcurrentMapCache】组件
* * 2)、key使用keyGenerator生成的,默认是SimpleKeyGenerator
* *
* *
* * 几个属性:
* * cacheNames/value:指定缓存组件的名字;将方法的返回结果放在哪个缓存中,是数组的方式,可以指定多个缓存;
* *
* * key:缓存数据使用的key;可以用它来指定。默认是使用方法参数的值 1-方法的返回值
* * 编写SpEL; #i d;参数id的值 #a0 #p0 #root.args[0]
* * getEmp[2]
* *
* * keyGenerator:key的生成器;可以自己指定key的生成器的组件id
* * key/keyGenerator:二选一使用;
* *
* *
* * cacheManager:指定缓存管理器;或者cacheResolver指定获取解析器
* *
* * condition:指定符合条件的情况下才缓存;
* * ,condition = "#id>0"
* * condition = "#a0>1":第一个参数的值》1的时候才进行缓存
* *
* * unless:否定缓存;当unless指定的条件为true,方法的返回值就不会被缓存;可以获取到结果进行判断
* * unless = "#result == null"
* * unless = "#a0==2":如果第一个参数的值是2,结果不缓存;
* * sync:是否使用异步模式
* @param id
* @return
*/
@Override
@Cacheable(value = {ModuleName.SRM_USER},key = "#id",condition = "#id.length()>0")
public ResponseResult queryById(String id) {
ResponseResult result = new ResponseResult();
SrmUser srmUser = srmUserMapper.selectById(id);
result.setBody(srmUser);
return result;
}
更新数据时同时更新注解
/**
* @CachePut:既调用方法,又更新缓存数据;同步更新缓存
* 修改了数据库的某个数据,同时更新缓存;
* 运行时机:
* 1、先调用目标方法
* 2、将目标方法的结果缓存起来
*
* 测试步骤:
* 1、查询1号员工;查到的结果会放在缓存中;
* key:1 value:lastName:张三
* 2、以后查询还是之前的结果
* 3、更新1号员工;【lastName:zhangsan;gender:0】
* 将方法的返回值也放进缓存了;
* key:传入的employee对象 值:返回的employee对象;
* 4、查询1号员工?
* 应该是更新后的员工;
* key = "#employee.id":使用传入的参数的员工id;
* key = "#result.id":使用返回后的id
* @Cacheable的key是不能用#result
* 为什么是没更新前的?【1号员工没有在缓存中更新】
*
*/
@Override
@CachePut(value = {ModuleName.SRM_USER},key = "#result.body.id")
public ResponseResult updateUser(SrmUser srmUser){
ResponseResult result = new ResponseResult();
return result;
// int res = srmUserMapper.updateById(srmUser);
// //交给统一处理结果,返回result
// return HandleResponseResult.checkUpdateValue(res,srmUser);
}
删除时同时删除注解
/**
* @CacheEvict:缓存清除
* key:指定要清除的数据
* allEntries = true:指定清除这个缓存中所有的数据
* beforeInvocation = false:缓存的清除是否在方法之前执行
* 默认代表缓存清除操作是在方法执行之后执行;如果出现异常缓存就不会清除
*
* beforeInvocation = true:
* 代表清除缓存操作是在方法运行之前执行,无论方法是否出现异常,缓存都清除
*
*
*/
@Override
@CacheEvict(value = {ModuleName.SRM_USER})
public ResponseResult deleteUser(String id) {
ResponseResult result = new ResponseResult();
int res = srmUserMapper.deleteById(id);
return HandleResponseResult.checkDeleteValue(res);
}