服务降级常见设置

  • mock=”force:return null”:消费方对该服务的方法调用都直接强制性返回 null 值,不发起远程调用。
  • mock=”fail:return null”:消费方对该服务的方法调用在失败后,再返回 null 值,不抛异常。
  • mock=”true”:消费方对该服务的方法调用在失败后,会调用消费方定义的服务降级Mock 类实例的相应方法。而该 Mock 类的类名为“业务接口名+Mock”,且放在与接口相同的包中。
  • mock=降级类的全限定性类名:与 mock=”true”功能类似,不同的是,该方式中的降级类名可以是任意名称,在任何包中

InvokerInvocationHandler.java

12.Dubbo服务降级源码阅读 - 图1

MockClusterInvoker.java

  1. public Result invoke(Invocation invocation) throws RpcException {
  2. Result result = null;
  3. // 获取mock属性值
  4. String value = directory.getUrl().getMethodParameter(invocation.getMethodName(), MOCK_KEY, Boolean.FALSE.toString()).trim();
  5. // 若没有设置mock属性,或mock属性值为false,则不具有降级功能
  6. if (value.length() == 0 || value.equalsIgnoreCase("false")) {
  7. //no mock 直接进行远程调用(不会降级)
  8. result = this.invoker.invoke(invocation);
  9. } else if (value.startsWith("force")) {
  10. // 代表开启强制降级,直接放弃远程调用,执行本地降级方法调用
  11. if (logger.isWarnEnabled()) {
  12. logger.warn("force-mock: " + invocation.getMethodName() + " force-mock enabled , url : " + directory.getUrl());
  13. }
  14. //force:direct mock 直接降级
  15. result = doMockInvoke(invocation, null);
  16. } else {
  17. //fail-mock
  18. try { // 远程调用
  19. result = this.invoker.invoke(invocation);
  20. } catch (RpcException e) {
  21. // 远程调用出现异常,则再进行服务降级
  22. if (e.isBiz()) {
  23. throw e;
  24. }
  25. if (logger.isWarnEnabled()) {
  26. logger.warn("fail-mock: " + invocation.getMethodName() + " fail-mock enabled , url : " + directory.getUrl(), e);
  27. }
  28. // 服务降级
  29. result = doMockInvoke(invocation, e);
  30. }
  31. }
  32. return result;
  33. }
  34. @SuppressWarnings({"unchecked", "rawtypes"})
  35. private Result doMockInvoke(Invocation invocation, RpcException e) {
  36. Result result = null;
  37. Invoker<T> minvoker;
  38. // 重新再从zk中获取一次最新的invoker
  39. List<Invoker<T>> mockInvokers = selectMockInvoker(invocation);
  40. // 若仍没有可用的invoker,则创建一个MockInvoker,否则返回第一个可用的invoker
  41. if (CollectionUtils.isEmpty(mockInvokers)) {
  42. minvoker = (Invoker<T>) new MockInvoker(directory.getUrl(), directory.getInterface());
  43. } else {
  44. minvoker = mockInvokers.get(0);
  45. }
  46. try {
  47. // 执行降级方法调用,跟踪这里
  48. result = minvoker.invoke(invocation);
  49. } catch (RpcException me) {
  50. if (me.isBiz()) {
  51. result = AsyncRpcResult.newDefaultAsyncResult(me.getCause(), invocation);
  52. } else {
  53. throw new RpcException(me.getCode(), getMockExceptionMessage(e, me), me.getCause());
  54. }
  55. } catch (Throwable me) {
  56. throw new RpcException(getMockExceptionMessage(e, me), me.getCause());
  57. }
  58. return result;
  59. }

MockInvoker.java

  1. public Result invoke(Invocation invocation) throws RpcException {
  2. // 获取<dubbo:method/>中的mock属性
  3. String mock = getUrl().getParameter(invocation.getMethodName() + "." + MOCK_KEY);
  4. if (invocation instanceof RpcInvocation) {
  5. ((RpcInvocation) invocation).setInvoker(this);
  6. }
  7. // 若<dubbo:method/>中没有设置mock,则获取<dubbo:reference/>中的mock
  8. // 这里就可以看出,方法级别的设置大于接口级别的设置。
  9. if (StringUtils.isBlank(mock)) {
  10. mock = getUrl().getParameter(MOCK_KEY);
  11. }
  12. if (StringUtils.isBlank(mock)) {
  13. throw new RpcException(new IllegalAccessException("mock can not be null. url :" + url));
  14. }
  15. // 解析mock中的值,并返回。为下面的业务做准备
  16. mock = normalizeMock(URL.decode(mock));
  17. // 处理mock以return开头的情况
  18. if (mock.startsWith(RETURN_PREFIX)) {
  19. // 取return后面的内容
  20. mock = mock.substring(RETURN_PREFIX.length()).trim();
  21. try {
  22. Type[] returnTypes = RpcUtils.getReturnTypes(invocation);
  23. Object value = parseMockValue(mock, returnTypes);
  24. return AsyncRpcResult.newDefaultAsyncResult(value, invocation);
  25. } catch (Exception ew) {
  26. throw new RpcException("mock return invoke error. method :" + invocation.getMethodName()
  27. + ", mock:" + mock + ", url: " + url, ew);
  28. }
  29. // 处理mock以throw开头的情况
  30. } else if (mock.startsWith(THROW_PREFIX)) {
  31. mock = mock.substring(THROW_PREFIX.length()).trim();
  32. if (StringUtils.isBlank(mock)) {
  33. throw new RpcException("mocked exception for service degradation.");
  34. } else { // user customized class
  35. Throwable t = getThrowable(mock);
  36. throw new RpcException(RpcException.BIZ_EXCEPTION, t);
  37. }
  38. } else { //impl mock 调用自定义降级类
  39. try {
  40. // 加载并实例化本地降级类
  41. Invoker<T> invoker = getInvoker(mock);
  42. return invoker.invoke(invocation);
  43. } catch (Throwable t) {
  44. throw new RpcException("Failed to create mock implementation class " + mock, t);
  45. }
  46. }
  47. }
  48. public static String normalizeMock(String mock) {
  49. if (mock == null) { // mock为null,则返回null
  50. return mock;
  51. }
  52. mock = mock.trim();
  53. if (mock.length() == 0) { // mock为空串,则返回空串
  54. return mock;
  55. }
  56. if (RETURN_KEY.equalsIgnoreCase(mock)) { // mock为return,则返回returnnull
  57. return RETURN_PREFIX + "null";
  58. }
  59. // mock为true、default、fail或force,则返回default
  60. if (ConfigUtils.isDefault(mock) || "fail".equalsIgnoreCase(mock) || "force".equalsIgnoreCase(mock)) {
  61. return "default";
  62. }
  63. // mock以fail:开头,则返回fail:后面的子串
  64. if (mock.startsWith(FAIL_PREFIX)) {
  65. mock = mock.substring(FAIL_PREFIX.length()).trim();
  66. }
  67. // mock以force:开头,则返回force:后面的子串
  68. if (mock.startsWith(FORCE_PREFIX)) {
  69. mock = mock.substring(FORCE_PREFIX.length()).trim();
  70. }
  71. // 若mock以return或throw,则将反引号替换为双引号
  72. if (mock.startsWith(RETURN_PREFIX) || mock.startsWith(THROW_PREFIX)) {
  73. mock = mock.replace('`', '"');
  74. }
  75. return mock;
  76. }
  77. private Invoker<T> getInvoker(String mockService) {
  78. Invoker<T> invoker = (Invoker<T>) MOCK_MAP.get(mockService);
  79. if (invoker != null) {
  80. return invoker;
  81. }
  82. // 加载指定业务接口
  83. Class<T> serviceType = (Class<T>) ReflectUtils.forName(url.getServiceInterface());
  84. // 构建出降级类,再加载并实例化
  85. T mockObject = (T) getMockObject(mockService, serviceType);
  86. // 将降级实例封装为一个invoker
  87. invoker = PROXY_FACTORY.getInvoker(mockObject, serviceType, url);
  88. if (MOCK_MAP.size() < 10000) {
  89. MOCK_MAP.put(mockService, invoker);
  90. }
  91. return invoker;
  92. }
  93. public static Object getMockObject(String mockService, Class serviceType) {
  94. // 若mockService的值为default,则构建出降级类名
  95. if (ConfigUtils.isDefault(mockService)) {
  96. mockService = serviceType.getName() + "Mock";
  97. }
  98. // 加载降级类
  99. Class<?> mockClass = ReflectUtils.forName(mockService);
  100. // 若降级类没有实现业务接口,则抛出异常
  101. if (!serviceType.isAssignableFrom(mockClass)) {
  102. throw new IllegalStateException("The mock class " + mockClass.getName() +
  103. " not implement interface " + serviceType.getName());
  104. }
  105. try {
  106. // 实例化
  107. return mockClass.newInstance();
  108. } catch (InstantiationException e) {
  109. throw new IllegalStateException("No default constructor from mock class " + mockClass.getName(), e);
  110. } catch (IllegalAccessException e) {
  111. throw new IllegalStateException(e);
  112. }
  113. }