1 服务降级策略概述
Dubbo的服务降级策略应用于服务消费端。设置Dubbo服务降级策略的目的,简单来说就是为了实现服务消费端在调用远程服务时,可以只执行mock方法,或者在调用失败时执行mock方法。
服务降级策略主要有以下两种:
(1)force策略。服务消费端不进行远程调用,直接执行mock方法(即服务降级方法),如返回设置的mock值、抛出异常或执行自定义mock类。
(1)mock = "force:return mock值"
(2)mock = "force:throw 抛出的异常名称"
(3)mock = "force:自定义的Mock类名"
(2)fail策略。服务消费端当调用远程接口失败时(非BIZ_EXCEPTION时),执行mock方法,如返回设置的mock值、抛出异常或执行自定义mock类。
(1)mock = "fail:return mock值"
(2)mock = "fail:throw 抛出的异常名称"
(3)mock = "fail:自定义的Mock类名"
服务降级主要用在以下场景:
- 当服务器压力剧增的情况下,根据当前业务情况及流量对一些服务有策略的降低服务级别,以释放服务器资源,保证核心任务的正常运行。
- 当服务响应超时或连接请求超时,不用继续等下去,而采用降级措施,以防止分布式服务发生雪崩效应。
- 在大促销之前通过降级开关关闭推荐、评价等对主流程没有影响的功能。大促销完毕后,再进行恢复。
- 在秒杀这种流量比较集中并且流量特别大的情况下,因为突发访问量特别大可能会导致系统支撑不了。这个时候可以采用限流来限制访问量,当达到阀值时,后续的请求被降级。
总的来说,服务降级策略主要用在保障核心服务的可用性,防止分布式服务发生雪崩效应,以及在服务器压力剧增或服务响应超时等情况下保证服务的正常运行。
2 设置服务降级策略
设置服务降级策略的主要方式有以下两种:
(1)通过dubbo控制台设置指定服务的降级策略。
(2)在服务消费端设置接口级别或方法级别的服务降级策略。举例如下。
设置接口级别的降级策略:
@Reference(mock = "fail:return null")
private TestService testService;
或者
<dubbo:reference id="testService" interface="com.hn.TestService"
protocol="dubbo" mock="fail:return null"/>
设置方法级别的降级策略:
<!-- 对getUserList方法进行降级,其它方法正常调用 -->
<dubbo:reference id="testService" interface="com.hn.TestService" protocol="dubbo">
<dubbo:method name="getUserList" mock="fail:return null"/>
</dubbo:reference>
3 服务降级策略过程剖析
在服务消费端发起远程调用的过程中,服务消费端首先调用 MockClusterInvoker 的 invoker() 方法。
(1)当没设置降级策略时,直接调用DubboInvoker的invoker()方法发起远程调用。
(2)当服务降级策略为“force策略”时,不进行远程调用,直接执行mock方法,如返回定义的mock值、抛出异常或执行自定义mock类。
(3)当服务降级策略不是“force策略”时,直接发起远程调用。当调用远程接口失败时(非BIZ_EXCEPTION时),执行mock方法,如返回设置的mock值、抛出异常或执行自定义mock类。
MockClusterInvoker的invoker()具体实现如下所示。
public Result invoke(Invocation invocation) throws RpcException {
Result result;
String value = getUrl().getMethodParameter(RpcUtils.getMethodName(invocation), MOCK_KEY, Boolean.FALSE.toString()).trim();
if (ConfigUtils.isEmpty(value)) {
//no mock
result = this.invoker.invoke(invocation);
} else if (value.startsWith(FORCE_KEY)) {
if (logger.isWarnEnabled()) {
logger.warn(CLUSTER_FAILED_MOCK_REQUEST,"force mock","","force-mock: " + RpcUtils.getMethodName(invocation) + " force-mock enabled , url : " + getUrl());
}
//force:direct mock
result = doMockInvoke(invocation, null);
} else {
//fail-mock
try {
result = this.invoker.invoke(invocation);
//fix:#4585
if (result.getException() != null && result.getException() instanceof RpcException) {
RpcException rpcException = (RpcException) result.getException();
if (rpcException.isBiz()) {
throw rpcException;
} else {
result = doMockInvoke(invocation, rpcException);
}
}
} catch (RpcException e) {
if (e.isBiz()) {
throw e;
}
if (logger.isWarnEnabled()) {
logger.warn(CLUSTER_FAILED_MOCK_REQUEST,"failed to mock invoke","","fail-mock: " + RpcUtils.getMethodName(invocation) + " fail-mock enabled , url : " + getUrl(),e);
}
result = doMockInvoke(invocation, e);
}
}
return result;
}
执行的mock方法为doMockInvoke(),具体实现如下所示。
private Result doMockInvoke(Invocation invocation, RpcException e) {
Result result;
Invoker<T> mockInvoker;
RpcInvocation rpcInvocation = (RpcInvocation)invocation;
rpcInvocation.setInvokeMode(RpcUtils.getInvokeMode(getUrl(),invocation));
List<Invoker<T>> mockInvokers = selectMockInvoker(invocation);
if (CollectionUtils.isEmpty(mockInvokers)) {
mockInvoker = (Invoker<T>) new MockInvoker(getUrl(), directory.getInterface());
} else {
mockInvoker = mockInvokers.get(0);
}
try {
result = mockInvoker.invoke(invocation);
} catch (RpcException mockException) {
if (mockException.isBiz()) {
result = AsyncRpcResult.newDefaultAsyncResult(mockException.getCause(), invocation);
} else {
throw new RpcException(mockException.getCode(), getMockExceptionMessage(e, mockException), mockException.getCause());
}
} catch (Throwable me) {
throw new RpcException(getMockExceptionMessage(e, me), me.getCause());
}
if (setFutureWhenSync || rpcInvocation.getInvokeMode() != InvokeMode.SYNC) {
// set server context
RpcContext.getServiceContext().setFuture(new FutureAdapter<>(((AsyncRpcResult)result).getResponseFuture()));
}
return result;
}
调用的核心方法为 org.apache.dubbo.rpc.support.MockInvoker#invoke 方法。具体执行分为三种情况:
(1)return->返回mock值;
(2)throw->抛出异常;
(3)执行自定义mock类。
public Result invoke(Invocation invocation) throws RpcException {
if (invocation instanceof RpcInvocation) {
((RpcInvocation) invocation).setInvoker(this);
}
String mock = getUrl().getMethodParameter(invocation.getMethodName(), MOCK_KEY);
if (StringUtils.isBlank(mock)) {
throw new RpcException(new IllegalAccessException("mock can not be null. url :" + url));
}
mock = normalizeMock(URL.decode(mock));
if (mock.startsWith(RETURN_PREFIX)) {
mock = mock.substring(RETURN_PREFIX.length()).trim();
try {
Type[] returnTypes = RpcUtils.getReturnTypes(invocation);
Object value = parseMockValue(mock, returnTypes);
return AsyncRpcResult.newDefaultAsyncResult(value, invocation);
} catch (Exception ew) {
throw new RpcException("mock return invoke error. method :" + invocation.getMethodName()
+ ", mock:" + mock + ", url: " + url, ew);
}
} else if (mock.startsWith(THROW_PREFIX)) {
mock = mock.substring(THROW_PREFIX.length()).trim();
if (StringUtils.isBlank(mock)) {
throw new RpcException("mocked exception for service degradation.");
} else { // user customized class
Throwable t = getThrowable(mock);
throw new RpcException(RpcException.BIZ_EXCEPTION, t);
}
} else { //impl mock
try {
Invoker<T> invoker = getInvoker(mock);
return invoker.invoke(invocation);
} catch (Throwable t) {
throw new RpcException("Failed to create mock implementation class " + mock, t);
}
}
}