接口有多个实现类时的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容器中的名称注入。
标签:
Web
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统