接口有多个实现类时的dubbo配置

在项目开发过程中,我使用了模板方法模式时,出现了一个接口4个实现类的场景,而这4个实现类的方法要被其他系统通过dubbo访问。之前只有一个实现类时的dubbo配置是这样:

<!-- 服务提供方 -->
<dubbo:service interface="com.xxx.api.DgtReportService" ref="dgtDailyReportService" version="1.0.0" timeout="30000" />
<!-- 服务消费方 -->
<dubbo:reference id="dubboDgtDailyReportService" check="false" interface="com.xxx.api.DgtReportService" version="1.0.0" retries="3"/>

代码中引用该service时通过@Autowired注入即可。

现在同一个接口有多个实现类时,可以通过dubbo提供的服务分组group来区分即可,配置如下:

<!-- 服务提供方(ref是具体实现类的bean名称) -->
<dubbo:service interface="com.xxx.api.DgtReportService" group="dailyReport" ref="dgtDailyReportService" version="1.0.0" timeout="30000" />
<dubbo:service interface="com.xxx.api.DgtReportService" group="dailyOrder"  ref="dgtDailyOrderService"  version="1.0.0" timeout="30000" />
<dubbo:service interface="com.xxx.api.DgtReportService" group="monthReport" ref="dgtMonthReportService" version="1.0.0" timeout="30000" />
<dubbo:service interface="com.xxx.api.DgtReportService" group="monthDetail" ref="dgtMonthDetailService" version="1.0.0" timeout="30000" />
<!-- 服务消费方 -->
<dubbo:reference id="dubboDgtDailyReportService" check="false" group="dailyReport" interface="com.xxx.api.DgtReportService" version="1.0.0" retries="3"/>
<dubbo:reference id="dubboDgtDailyOrderService"  check="false" group="dailyOrder"  interface="com.xxx.api.DgtReportService" version="1.0.0" retries="3"/>
<dubbo:reference id="dubboDgtMonthReportService" check="false" group="monthReport" interface="com.xxx.api.DgtReportService" version="1.0.0" retries="3"/>
<dubbo:reference id="dubboDgtMonthDetailService" check="false" group="monthDetail" interface="com.xxx.api.DgtReportService" version="1.0.0" retries="3"/>

Java代码中通过@Resource注解引入对应的dubbo服务:

@Service
public class DgtRerportService {

// 这里的name和<dubbo:reference />中的id值一致 @Resource(name
= "dubboDgtDailyReportService") private com.xxx.api.DgtReportService dubboDgtDailyReportService; @Resource(name = "dubboDgtDailyOrderService") private com.xxx.api.DgtReportService dubboDgtDailyOrderService; @Resource(name = "dubboDgtMonthReportService") private com.xxx.api.DgtReportService dubboDgtMonthReportService; @Resource(name = "dubboDgtMonthDetailService") private com.xxx.api.DgtReportService dubboDgtMonthDetailService; }

相关知识点补充:

@Autowired
功能:引入由Spring容器管理的bean。
特点:byType自动注入,根据类型注入。

@Resource
功能:引入由Spring容器管理的bean。
特点:byName自动注入,根据Service在Spring容器中的名称注入。

posted on 2022-11-15 14:26  阿泰555  阅读(1129)  评论(0编辑  收藏  举报

导航