目的:分组聚合中,自定义合并策略,合并不同分组返回的结果
实现:
首先,假设提供方provider提供了UserService接口的多个实现,分别为UserServiceImpl和AnotherUserServiceImpl,分别隶属于db和mock组, 消费方将调用这两个服务,并按照自定义策略合并他们的返回结果,作为最终结果。整体结构如下:
代码结构如下:
provider方:
service
-- UserServiceImpl.java # 实现从数据库读取用户数据
-- AnotherUserServiceImpl.java # mock用户数据作为返回结果
resources
-- dubbo-provider.xml
dubbo-provider.xml中配置service如下
<dubbo:service ref="userService" group="db" interface="com.patty.dubbo.api.service.UserService"/> <dubbo:service ref="anotherUserService" group="mock" interface="com.patty.dubbo.api.service.UserService"/>
consumer方:
service
-- MyMerger.java # 扩展Merger接口,实现自定义的合并策略
resources
-- dubbo-consumer.xml
-- META-INF.dubbo
-- com.alibaba.dubbo.rpc.cluster.Merger # 纯文本文件, 映射自定义的merger名称到相应的实现类
本例中,映射内容为:
myMerger=com.patty.dubbo.consumer.service.MyMerger
dubbo-consumer.xml中配置merger合并器:
<dubbo:reference id="userService" group="*" interface="com.patty.dubbo.api.service.UserService" timeout="10000" retries="3" mock="true"> <dubbo:method name="findAllUsers" merger="myMerger"> </dubbo:method> </dubbo:reference>
MyMerger实现如下:
public class MyMerger implements Merger<List<UserVo>> { @Override public List<UserVo> merge(List<UserVo>... userVoLists) { ArrayList<UserVo> result = new ArrayList<>(); for (List<UserVo> userVoList : userVoLists) { for (UserVo userVo : userVoList) { if (userVo.getwId().equals("10")) { userVoList.remove(userVo); } } result.addAll(userVoList); } return result; } }
该类实现 com.alibaba.dubbo.rpc.cluster.Merger接口。
具体实现参考:https://github.com/pattywgm/dubbo-demo/tree/577c289d0ef3b0e45361e1ac6141ccb2b1cdb8c3