dubbo学习(八)dubbo项目搭建--消费者(服务消费者)
PS: 项目架子以及工程间的maven依赖配置暂时省略,后续看情况可能会单独写一篇文章捋捋框架结构,先马克~
配置和启动
1.pom文件引入dubbo和zookeeper的操作客户端(此步骤与生产者配置一致)
<!--引入dubbo--> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <version>2.6.2</version> </dependency> <!--这里使用zookeeper作为注册中心,引入操作zookeeper的客户端--> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-framework</artifactId> <version>2.12.0</version> </dependency> <!--框架依赖end-->
2.新建一个consumer的xml文件,用于配置消费者的信息
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://dubbo.apache.org/schema/dubbo" xmlns:component="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--配置扫描包的路径--> <component:component-scan base-package="com.zhanghaoBF.gmall.service.impl"></component:component-scan> <!--1.指定当前服务/应用的名字(同样的服务名字相同,但是不要和其他服务同名)--> <dubbo:application name="order-service"></dubbo:application> <!--2.指定注册中心的位置--> <!--写法1--> <dubbo:registry address="zookeeper://127.0.0.1:2181"></dubbo:registry> <!--写法2--> <!--<dubbo:registry protocol="zookeeper" address="127.0.0.1:2181"></dubbo:registry>--> <!--声明需要调用的远程服务的接口:生成远程服务代理--> <dubbo:reference interface="dubbo.service.user.UserService" id="userService"></dubbo:reference> </beans>
3.创建一个消费者启动类Consumer.java
public class Consumer { public static void main(String[] args) throws Exception { //读取IOC容器 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("consumer.xml"); //从容器中获取OrderService组件对象 OrderService orderService = context.getBean(OrderService.class); //调用orderService服务,服务实现里远程调用UserService的dubbo服务 orderService.initOrder("1"); //设置阻塞 System.out.println("调用完成...."); System.in.read(); // 此代码功能:按任意键退出 } }
4.启动
右键debug启动类后,打开上一章讲解的控制台,可看到消费者也已经可以在控制台看到了,欸嘿,有点意思噻~
PS:启动前需要先启动zk和控制台才能实现下图的效果
分类:
Dubbo
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律