当前位置: 首页 > 后端技术 > Java

重试机制!

时间:2023-04-02 01:38:28 Java

1.try-catch-redo简单重试模式try{result=uploadToOdps(paramMap);如果(!结果){Thread.sleep(1000);uploadToOdps(paramMap);//重试一次}}catch(Exceptione){Thread.sleep(1000);uploadToOdps(paramMap);//一次重试实现简单,但代码冗余,无侵入,发表评论即可3.使用For循环实现for(inti=0;i<3;i++){try{xxx;休息;}赶上(异常e){xxx;线程.睡眠(1000);继续;}}4.使用AOP切面实现@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic@interfaceRetryable{/***可重试的异常类型。*@return重试异常类型*/Classvalue()默认RuntimeException。班级;/***包含第一次失败*@return最大尝试次数(包括第一次失败),默认3次*/intmaxAttempts()default3;}@Aspect@ComponentpublicclassRetryAspect{@Pointcut("execution(public*com.github.houbb.retry.aop..*.*(..))&&"+"@annotation(com.github.houbb.retry.aop.annotation.Retryable)")publicvoidmyPointcut(){}@Around("myPointcut()")publicObjectaround(ProceedingJoinPointpoint)throwsThrowable{Methodmethod=getCurrentMethod(point);可重试retryable=method.getAnnotation(Retryable.class);//1。最大次数判定intmaxAttempts=retryable.maxAttempts();如果(maxAttempts<=1){返回point.proceed();}//2。异常处理inttimes=0;最后一堂课exceptionClass=retryable.value();while(times=maxAttempts||!e.getClass().isAssignableFrom(exceptionClass)){thrownewThrowable(e);}}}返回空值;}privateMethodgetCurrentMethod(ProceedingJoinPointpoint){try{签名sig=point.得到签名();MethodSignaturemsig=(MethodSignature)sig;对象目标=点。获取目标();回归目标。getClass().getMethod(msig.getName(),msig.getParameterTypes());}catch(NoSuchMethodExceptione){thrownewRuntimeException(e);}}}

最新推荐
猜你喜欢