自定义AOP实现注解式redis缓存

先说怎么使用,超简单

 

注解类
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);
    }

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值