dubbo 服务降级
官网:https://dubbo.apache.org/zh/docs/advanced/local-mock/
服务降级
应用:消费端服务调用失败,不抛出异常,返回默认的数据
服务降级配置示例
# 同目录下查找服务降级类:com.foo.service.BarServiceMock
<dubbo:reference interface="com.foo.service.BarService" mock="true" />
# 指定本地服务降级类:com.foo.service.impl.BarServiceMock
<dubbo:reference interface="com.foo.service.BarService" mock="com.foo.service.impl.BarServiceMock" />
# 方法级别服务容错:方法名后面加".mock"
<dubbo:reference id="demoService" check="false" interface="com.foo.BarService">
<dubbo:parameter key="sayHello.mock" value="force:return fake"/>
</dubbo:reference>
mock 可选值
true:开启服务降级
false:不开启服务降级
# return:返回一个字符串表示的对象
empty:基本类型返回对应的默认值、集合类返回空值,如:return empty
null:返回null
true:返回true
false:返回false
JSON字符串:返回json字符串反序列化后的对象
# throw:抛出异常对象
抛出rpcException:<dubbo:reference interface="com.foo.BarService" mock="throw" />
抛出自定义异常:<dubbo:reference interface="com.foo.BarService" mock="throw com.foo.MockException" />
# force:强制使用mock,不发起服务调用,可与return、throw组合使用
# fail:服务调用失败时,执行mock(默认行为),可与return、throw组合使用
强制返回fake:<dubbo:reference interface="com.foo.BarService" mock="force:return fake" />
强制抛出异常:<dubbo:reference interface="com.foo.BarService" mock="force:throw com.foo.MockException" />
消费端应用启动时,在创建failoverClusterInvoker的过程中,会用MockClusterWrapper包装,调用栈如下:
# 创建FailoverClusterInvoker对象,默认创建该对象
at org.apache.dubbo.rpc.cluster.support.FailoverClusterInvoker.<init>(FailoverClusterInvoker.java:52)
# join操作
at org.apache.dubbo.rpc.cluster.support.FailoverCluster.doJoin(FailoverCluster.java:33)
at org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster.join(AbstractCluster.java:58)
# MockClusterWrapper:服务降级包装类
at org.apache.dubbo.rpc.cluster.support.wrapper.MockClusterWrapper.join(MockClusterWrapper.java:39)
# 创建invoker
at org.apache.dubbo.registry.integration.RegistryProtocol.doCreateInvoker(RegistryProtocol.java:564)
# 获取invoker
at org.apache.dubbo.registry.integration.InterfaceCompatibleRegistryProtocol.getInvoker(InterfaceCompatibleRegistryProtocol.java:58)
# MigrationInvoker类
at org.apache.dubbo.registry.client.migration.MigrationInvoker.refreshInterfaceInvoker(MigrationInvoker.java:448)
at org.apache.dubbo.registry.client.migration.MigrationInvoker.migrateToApplicationFirstInvoker(MigrationInvoker.java:239)
# MigrationRuleHandler类
at org.apache.dubbo.registry.client.migration.MigrationRuleHandler.refreshInvoker(MigrationRuleHandler.java:73)
at org.apache.dubbo.registry.client.migration.MigrationRuleHandler.doMigrate(MigrationRuleHandler.java:57)
- locked <0x21db> (a org.apache.dubbo.registry.client.migration.MigrationRuleHandler)
at org.apache.dubbo.registry.client.migration.MigrationRuleListener.onRefer(MigrationRuleListener.java:241)
# RegistryProtocol类
at org.apache.dubbo.registry.integration.