1.application.yaml中添加cache配置
XML
spring:
cache:
type: redis
redis:
time-to-live: 72000000
key-prefix: 'redis:cache:'
use-key-prefix: true
cache-null-values: true
2.封装RedisCache配置类
java
@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class RedisCacheConfig {
@Bean
public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
// config = config.entryTtl();
config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
CacheProperties.Redis redisProperties = cacheProperties.getRedis();
//将配置文件中所有的配置都生效
if (redisProperties.getTimeToLive() != null) {
config = config.entryTtl(redisProperties.getTimeToLive());
}
if (redisProperties.getKeyPrefix() != null) {
config = config.computePrefixWith(cacheName -> redisProperties.getKeyPrefix() + cacheName);
}
if (!redisProperties.isCacheNullValues()) {
config = config.disableCachingNullValues();
}
if (!redisProperties.isUseKeyPrefix()) {
config = config.disableKeyPrefix();
}
return config;
}
}
3.封装RedisCache缓存Key生成器
java
/**
* @ClassName redisCacheKeyGenerator
* @description: Redis缓存key 生成策略
*/
@Slf4j
@Component("redisCacheKeyGenerator")
public class RedisCacheKeyGenerator implements KeyGenerator {
private final static int NO_PARAM_KEY = 0;
public static final char SP = ':';
@Autowired(required = false)
private CacheManager cacheManager;
@PostConstruct
public void init() {
log.info("cacheManager:{}",cacheManager);
}
@Override
public Object generate(Object target, Method method, Object... parameters) {
StringBuilder strBuilder = new StringBuilder(30);
// 类名
strBuilder.append(SP);
// 方法名
strBuilder.append(method.getName());
strBuilder.append(SP);
if (parameters.length > 0) {
// 参数值
for (Object object : parameters) {
if (isSimpleValueType(object.getClass())) {
strBuilder.append(object);
} else {
strBuilder.append(JSONUtil.toJsonStr(object).hashCode());
}
}
} else {
strBuilder.append(NO_PARAM_KEY);
}
log.info("生成缓存序列:{}",strBuilder);
return strBuilder.toString();
}
/**
* 判断是否是简单值类型.包括:基础数据类型、CharSequence、Number、Date、URL、URI、Locale、Class;
*
* @param clazz
* @return
*/
public static boolean isSimpleValueType(Class<?> clazz) {
return (ClassUtils.isPrimitiveOrWrapper(clazz) || clazz.isEnum() || CharSequence.class.isAssignableFrom(clazz)
|| Number.class.isAssignableFrom(clazz) || Date.class.isAssignableFrom(clazz) || URI.class == clazz
|| URL.class == clazz || Locale.class == clazz || Class.class == clazz);
}
}
4.Service类中应用RedisCache
java
@Service
@CacheConfig(cacheNames = "productAlbum",keyGenerator = "redisCacheKeyGenerator")
public class ProductAlbumServiceImpl extends ServiceImpl<ProductAlbumMapper, ProductAlbum> implements IProductAlbumService {
@Override
@Transactional(rollbackFor = Exception.class)
@Caching(
evict = {
@CacheEvict(key = "':getAlbumPics_'+#productSn"),
@CacheEvict(key = "':getAlbumPicsBySn_'+#productSn")
}
)
public void saveAlbumPics(String productSn, String pic) {
// 业务代码
}
@Override
@Caching(
evict = {
@CacheEvict(key = "':getAlbumPics_'+#productSn"),
@CacheEvict(key = "':getAlbumPicsBySn_'+#productSn")
}
)
public void doAlbumPics(String productSn,List<ProductAlbumResp> albumList) {
// 业务代码
}
@Override
@Cacheable(key = "':getAlbumPics_'+#productSn")
public String getAlbumPics(String productSn) {
// 业务代码
}
@Override
@Cacheable(key = "':getAlbumPicsBySn_'+#productSn")
public List<ProductAlbumResp> getAlbumPicsBySn(String productSn) {
// 业务代码
}
@Override
@Caching(
evict = {
@CacheEvict(key = "':getAlbumPics_'+#productSn"),
@CacheEvict(key = "':getAlbumPicsBySn_'+#productSn")
}
)
public void saveAlbumPicsByNotExist(String productSn, String pic) {
// 业务代码
}
}