1、引入以下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2、添加如下配置
spring:
redis:
host: 192.168.209.128
port: 6379
cache:
type: redis
redis:
time-to-live: 3600000
cache-null-values: true #允许缓存为null,防止缓存穿透
3、在启动类或配置类中添加@EnableCaching注解,并配置json序列化,代码如下
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
RedisCacheConfiguration redisCacheConfiguration(){
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
config=config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
config=config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return config;
}
}
我就是因为没有添加@EnableCaching注解,导致缓存不起作用,无法添加缓存,折腾了很久才发现,特此说明。
4、给servie层中的方法添加缓存注解
@Override
@CacheEvict(value = "HouseResources",allEntries = true)
public boolean save(HouseResources houseResources){
int result = apiHouseResourceService.saveHouseResources(houseResources);
return result==1;
}
@Override
@Cacheable(value = "HouseResources",key = "'queryList_'+#current+'_'+#size")
public TableResult<HouseResources> queryList(HouseResources houseResources, Integer current, Integer size) {
PageInfo<HouseResources> pageInfo = apiHouseResourceService.queryHouseResourcesList(current, size, houseResources);
return new TableResult<HouseResources>(pageInfo.getRecords(),new Pagination(current,size,pageInfo.getTotal()));
}