技术日常系列今天同事说他非常牛逼,搞了一个很棒的设计
分享
今天同事跑过来跟我说,他有了一个牛逼plus的设计,他说他设计一个很牛逼的程序。
我问他:什么?
他:我设计了一个redis切面。
我:有啥用。
他:每次要用到redis时,只要注解引用一下就好了,省了很多代码,非常方便
我;那我看看。
那么他如何写的一个redis缓存切,下面我们来看看第一步自定义注解@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface IcCacheable { String key(); //支持spel } 第二步 定义切面@Component @Aspect public class IcCacheableAspect { @Autowired private CacheUtils cacheUtils; //支持spel语法 ExpressionParser parser = new SpelExpressionParser(); LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer(); @Around(value = "@annotation(icCacheable)") public Object invoked(ProceedingJoinPoint pjp, IcCacheable icCacheable) throws Throwable { Object[] args = pjp.getArgs(); Method method = ((MethodSignature) pjp.getSignature()).getMethod(); String spel = icCacheable.key(); String[] params = discoverer.getParameterNames(method); EvaluationContext context = new StandardEvaluationContext(); for (int len = 0; len < params.length; len++) { context.setVariable(params[len], args[len]); } //得到表达式结果 Expression expression = parser.parseExpression(spel); String cacheKey = expression.getValue(context, String.class); //执行之前先看缓存有没有,没有在执行 Object cachers = cacheUtils.get(cacheKey); if (cachers != null) { return cachers; } else { Object proceedObject = pjp.proceed(); cacheUtils.put(cacheKey, proceedObject); return proceedObject; } } } 第三步 调用 @IcCacheable(key = ""vr_biz_to_batch:"+#batchId") public VrBizToBatch queryBizInfo(String batchId) { QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("batch_id", batchId); try { VrBizToBatch bizToBatch = vrBizToBatchService.getOne(queryWrapper); if (bizToBatch == null) { throw new IcBizException(EnumBizError.NO_SCENE_FOR_BATCH_ERROR.getCode(), EnumBizError.NO_SCENCE_ERROR.getMsg()); } return bizToBatch; } catch (Exception e) { throw new IcBizException(EnumDbError.QUERY_ERRO.getCode(), EnumDbError.QUERY_ERRO.getMsg()); } }留个关注
《日常分享系列》 ,会持续更新,想了解的朋友可以关注 ,文章有帮助的话可以长按点赞 有惊喜!!!文章比较长,大家可以先 收藏 、转发 后再看,有什么补充可以在下面评论 ,谢谢大家!