java调⽤接⼝失败重调_springboot下接⼝调⽤失败重试⽅案背景:
在项⽬开发中,有时候会出现接⼝调⽤失败,本⾝调⽤⼜是异步的,如果是因为⼀些⽹络问题请求超时,总想可以重试⼏次把任务处理掉。
⼀些RPC框架,⽐如dubbo都是有重试机制的,但是并不是每⼀个项⽬多会使⽤dubbo框架,常规的⼩项⽬有时候直接使⽤http进⾏不同
项⽬之间的交互。
个⼈想法:
使⽤spring aop和⾃定义注解来,建⽴⼀套重试机制。
根据切⼊点和⾃定义注解,来完成重试⼯作。
exps:
定义⼀个注解:
1 importorg.springframework.stereotype.Component;2
3 importjava.lang.annotation.Documented;
4 importjava.lang.annotation.ElementType;5
importjava.lang.annotation.Retention;6 importjava.lang.annotation.RetentionPolicy;7 importjava.lang.annotation.Target;8
9 @Retention(RetentionPolicy.RUNTIME)10 @Target(ElementType.METHOD)11 @Documented12 @Component13 public
@interfaceRetryProcess {14 //重试的次数
15 int value() default 1;16 }
importorg.aspectj.lang.JoinPoint;importorg.aspectj.lang.annotation.AfterThrowing;importorg.aspectj.lang.annotation.Aspect;imp
@Aspect
@Componentpublic classAspectExceptionInterceptor {private final Logger logger =
springboot aop
@AfterThrowing(pointcut=("execution(* l..*(..)) &&
@pluspent.RetryProcess)"))public voidtryAgain(JoinPoint point) {
logger.info("------------开始重试------------");try{
Object Target();
Field field= Class().getDeclaredField("threadLocal");
field.setAccessible(true);
ThreadLocal threadLocal = (ThreadLocal) (object);
MethodSignature methodSignature=(MethodSignature) Signature();
RetryProcess retryProcess= Method().getAnnotation(RetryProcess.class);if
(().intValue()
logger.info("开始重试第"+index);
MethodInvocationProceedingJoinPoint methodPoint=((MethodInvocationProceedingJoinPoint) point);
methodPoint.proceed();
}
}catch(Throwable throwable) {//("重试失败",throwable);
tryAgain(point);
}
}
}
测试代码:
@RetryProcess(value = 2)
@RequestMapping("/hero")
@ResponseBody
public String doIt2() {
//该接⼝会抛出异常,启动进⾏重试机制testService.doProcess();
return "success";
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。