业务层使用:
@Cacheable(value = "dictionary#1800", key = "#root.targetClass.simpleName +':'+ #root.methodName +':'+ #code")
public Object findByCode(String code) {
//业务
}
配置:
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisOperations;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class MyRedisCacheManager extends RedisCacheManager {
/**
* 过期时间分隔符
*/
private static final String TTLSEPARATOR = "#";
private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap(16);
/**
* 过期时间, 单位为 秒
*/
private long defaultExpiration = 0;
public MyRedisCacheManager(RedisOperations redisOperations) {
super(redisOperations);
}
@Override
public Cache getCache(String name) {
long expiredTime = defaultExpiration;
if (name.contains(TTLSEPARATOR)) {
String[] split = name.split(TTLSEPARATOR);
String cacheName = split[0];
try {
expiredTime = Double.valueOf(split[1]).longValue();
} catch (Exception e) {
e.printStackTrace();
}
Cache cache = this.cacheMap.get(name);
if (cache != null) {
return cache;
} else {
synchronized (this.cacheMap) {
cache = this.cacheMap.get(name);
if (cache == null) {
cache = new RedisCache(cacheName, null, super.getRedisOperations(), expiredTime);
if (cache != null) {
cache = this.decorateCache(cache);
this.cacheMap.put(name, cache);
}
}
return cache;
}
}
}
return super.getCache(name);
}
}
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@CacheConfig
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
//设置序列化Key的实例化对象
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置序列化Value的实例化对象
ObjectMapper mapper = new ObjectMapper();
mapper.findAndRegisterModules();
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer(mapper);
redisTemplate.setValueSerializer(serializer);
MyRedisCacheManager mrc = new MyRedisCacheManager(redisTemplate);
return mrc;
}
}