这块内容相对简单些,先来看一下概念:
- 降级:当服务出现异常时,返回指定的信息,可以是异常或者指定的字符串;但是,它是发起调用时出错的情况下才会触发;
- 熔断:熔断更像是一种开头,比如A调B熔断开启时,不进行B的调用,直接返回指定的值;
使用方式:mock=“[fail|force]return|throw xxx”
fail:表示调用失败时,执行mock方法;如果不指定关键字默认为 fail
force:表示不执行远程调用,直接调用mock方法;
return表示指定返回结果,throw表示抛出指定异常;
当调用目标接口出现异常时,返回return 一个空,就是return null;但是,如果提供方抛出了一些Runtime或者是空指针之类的异常的话,是不会拦截处理的,它只处理:RpcException
示例:
<dubbo:reference id="demoService" interface="com.xxx.service.DemoService" mock="return" />
和上面是一样的效果
<dubbo:reference id="demoService" interface="com.xxx.service.DemoService" mock="return null" />
满足条件,响应“aaa”
<dubbo:reference id="demoService" interface="com.xxx.service.DemoService" mock="fail:return aaa" />
<dubbo:reference id="demoService" interface="com.xxx.service.DemoService" mock="force:return true" />
<dubbo:reference id="demoService" interface="com.xxx.service.DemoService" mock="fail:throw " />
mock="force:throw java.lang.NullPointerException"
源码分析
入口在:com.alibaba.dubbo.rpc.cluster.support.wrapper.MockClusterInvoker#invoke
public Result invoke(Invocation invocation) throws RpcException {
Result result = null;
// 获取mock配置,如果未配置,则默认是false
String value = directory.getUrl().getMethodParameter(invocation.getMethodName(), Constants.MOCK_KEY, Boolean.FALSE.toString()).trim();
if (value.length() == 0 || value.equalsIgnoreCase("false")) {
//未配置mock则正常的进行调用,如果出现异常等信息向上抛出即可;
result = this.invoker.invoke(invocation);
} else if (value.startsWith("force")) {
// 如果mock="force",表示不进行远程调用,直接返回指定的mock信息;
if (logger.isWarnEnabled()) {
logger.info("force-mock: " + invocation.getMethodName() + " force-mock enabled , url : " + directory.getUrl());
}
//force:direct mock
// 调用 MockInvoker.invoke方法
// MockInvoker.invoke的逻辑就是,如果是mock="fail:return" 则将后面的return内容返回,如果是mock="fail:throw"则将异常响应
result = doMockInvoke(invocation, null);
} else {
//如果mock="fail",则进行远程调用,如果远程调用超时,则处理;
try {
// 进行远程调用
result = this.invoker.invoke(invocation);
} catch (RpcException e) {
if (e.isBiz()) {
throw e;
} else {
if (logger.isWarnEnabled()) {
logger.warn("fail-mock: " + invocation.getMethodName() + " fail-mock enabled , url : " + directory.getUrl(), e);
}
// 如果远程调用响应RpcException,则doMockInvoke生成
// 判断是mock="return"还是throw生成一个结果;
result = doMockInvoke(invocation, e);
}
}
}
return result;
}
private Result doMockInvoke(Invocation invocation, RpcException e) {
Result result = null;
Invoker<T> minvoker;
// 如果mock="force"或者fail,则这里返回的是null;
List<Invoker<T>> mockInvokers = selectMockInvoker(invocation);
if (mockInvokers == null || mockInvokers.isEmpty()) {
// 所以这里会创建一个MockInvoker
minvoker = (Invoker<T>) new MockInvoker(directory.getUrl());
} else {
minvoker = mockInvokers.get(0);
}
try {
result = minvoker.invoke(invocation);
} catch (RpcException me) {
if (me.isBiz()) {
result = new RpcResult(me.getCause());
} else {
throw new RpcException(me.getCode(), getMockExceptionMessage(e, me), me.getCause());
}
} catch (Throwable me) {
throw new RpcException(getMockExceptionMessage(e, me), me.getCause());
}
return result;
}