先说怎么使用,超简单
注解类
public @interface AppsinnovaCache {
String desc() default ""; //描述
long expire() default 60; //缓存过期时间 单位:秒
String key();
boolean param() default false; //缓存key是否需要拼凑参数
}
//无参数缓存的
@AppsinnovaCache(key="你的KEY",expire=5,desc="")
public List<T> findAll() {
return namedParameterJdbcTemplate.query(sql,new BeanPropertyRowMapper<>(T.class));
}
//根据参数缓存的
@AppsinnovaCache(key="BD_ONE_LANG_TEXT_KEY",expire=600,desc="获取单个文案缓存",param = true)
public LanguageTextEntity findByKey(String key) {
List<LanguageTextEntity> languageTextEntityList =findByKey(textKeySet);
return languageTextEntityList.isEmpty() ? null : languageTextEntityList.get(0);
}
@Resource
RedisCommonDao redisCommonDao;
@Around("@annotation(appsinnovaCache)")
public Object authentication(final ProceedingJoinPoint jp, AppsinnovaCache appsinnovaCache) throws Throwable {
return this.aroundCacheMethod(jp,appsinnovaCache);
}
private Object aroundCacheMethod(ProceedingJoinPoint jp,AppsinnovaCache appsinnovaCache) throws Throwable {
log.info("key:{},expire:{},id:{},desc:{}",appsinnovaCache.key(),appsinnovaCache.expire(),
appsinnovaCache.param(),appsinnovaCache.desc());
Object[] args = jp.getArgs();
Class<?>[] paramsCls = new Class<?>[args.length];
for (int i = 0; i < args.length; ++i) {
paramsCls[i] = args[i].getClass();
}
Method method = jp.getTarget().getClass().getMethod(jp.getSignature().getName(), paramsCls);
String cacheKey=appsinnovaCache.key();
try {
if(appsinnovaCache.param()){
cacheKey+=StringUtils.join(args, "_");
}
String dataCacheStr=redisCommonDao.get(cacheKey);
if(StringUtils.isBlank(dataCacheStr)){
//缓存找不到则穿透,获取后并写入redis
Object result=jp.proceed();
redisCommonDao.setEx(cacheKey, JsonUtils.writeValueAsString(result),appsinnovaCache.expire());
return result;
}
//找到缓存,反序列化成对象
return JsonUtils.readValue(cacheValue, new TypeReference<Object>() {
@Override
public Type getType() {
return methodSignature.getMethod().getGenericReturnType();
}
});
} catch (Exception e) {
log.error("e;{}",e);
return jp.proceed();
}
}
//下面是json工具类,可替换成自己的序列号反序列化方法
public static <T> T readValue(String jsonstr, Class<T> clazz) {
return readValue(MAPPER, jsonstr, clazz);
}
public static <T> T readValue(ObjectMapper mapper, String jsonstr, Class<T> clazz) {
try {
return null == jsonstr ? null : mapper.readValue(jsonstr, clazz);
} catch (Exception e) {
logger.warn("content cannot be deserialized:{}, message:{}", jsonstr, e.getLocalizedMessage());
return null;
}
}
public static final ObjectMapper MAPPER;
public static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
static {
MAPPER = new ObjectMapper();
MAPPER.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}