- 导入依赖
- 指定缓存类型
- @EnableCache
- 使用注解
<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>
cache:
type: redis
注解
@Caching 组合以上多个操作
@CacheEvict 删除缓存
@Cacheable 保存到缓存
@CachePut 不影响方法执行更新缓存
@CacheConfig 在类级别共享缓存的相同配置
配置
json需要配一下,不然序列化复杂数据类型会抛异常
@Configuration
@EnableCaching // 默认配置缓存null(缓存穿透)
public class CacheConfig {
@Resource
RedisCacheConfiguration config;
@Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMillis(3000)) // 过期时间
.disableKeyPrefix() // key 不添加前缀
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); // value 使用JSON序列化方式
}
}
@Cacheable 保存到缓存
@Override
@Cacheable(cacheNames = "catalogCache", key = "'catalog'")
public Map<String, List<Catalog2VO>> getCatalogJson() {
RLock lock = client.getLock("catalogLock");
lock.lock();
Map<String, List<Catalog2VO>> data = null;
try {
data = getCatalogJsonByDB();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return data;
}
@CacheEvict 删除缓存
@Override
@CacheEvict(cacheNames = "catalogCache", key = "'catalog'")
public void updateCatelog(CategoryEntity entity) {
this.updateById(entity);
}
- 删除一个缓存分区下的所有键
@CacheEvict(cacheNames = "catalogCache",allEntries = true)
@Caching 组合以上多个操作
@Caching(cacheable = {
@Cacheable(cacheNames = "catalogCache", key = "'catalog'"),
@Cacheable(cacheNames = "catalogCache", key = "'catalog1'")
})