创建熔断注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyHystrixCommand {
long timeout() default 1000;
String callBack() default "";
}
创建 AOP 类
@Aspect
@Component
public class MyHystrixAop {
private ExecutorService executorService = Executors.newFixedThreadPool(10);
@Pointcut("@annotation(MyHystrixCommand)")
public void pointCut(){}
@Around("pointCut() && @annotation(myHystrixCommand)")
public Object doPointCut(ProceedingJoinPoint joinPoint,MyHystrixCommand myHystrixCommand) throws InterruptedException, ExecutionException, TimeoutException {
Future future = executorService.submit(()->{
try {
return joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
});
Object result = null;
try {
result = future.get(myHystrixCommand.timeout(), TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException |TimeoutException e) {
e.printStackTrace();
future.cancel(true);
if(StringUtils.isEmpty(myHystrixCommand.callBack())){
throw e;
}
}
if(result == null){
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
Class<?>[] parameterTypes = method.getParameterTypes();
Method m = null;
try {
m = joinPoint.getTarget().getClass().getMethod(myHystrixCommand.callBack(), parameterTypes);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
return m.invoke(joinPoint.getTarget(),joinPoint.getArgs());
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
}
创建 Controller 类
@RestController
@RequestMapping("/hystrix/test")
public class MyHystrixController {
@MyHystrixCommand(timeout = 2000,callBack = "callBack")
@RequestMapping("/req")
public String getUserInfoById(String userId){
return "请求成功";
}
public String callBack(String userId){
return "请求熔断了...";
}
}
正常测试,超时时间是 2000 毫秒

我们让 AOP 类中请求目标方法休息 3000 毫秒试试看

结果请求超时了,调用了熔断方法
