Dubbo提供者配置(spring文件方式配置)
服务提供者user-service-provider
1.将服务提供者注册到注册中心
(1)导入Dubbo依赖与操作Zookeeper的客户端(curator)
<!-- 引入dubbo --> <!-- https://mvnrepository.com/artifact/com.alibaba/dubbo --> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <version>2.6.2</version> </dependency> <!--操作zookeeper的客户端,dubbo在2.6以后版本用的是curator,之前是zkclient--> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-framework</artifactId> <version>2.12.0</version> </dependency>
(2)配置配置服务提供者(provider.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
<!-- 指定当前服务/应用的名字(同样的服务名字相同,不要和别的服务同名) -->
<dubbo:application name="user-service-provider" />
<!-- 指定注册中心的位置 -->
<dubbo:registry address="zookeeper://127.0.0.1:2181" />
<!-- 指定通信规则(通信协议?通信端口) -->
<dubbo:protocol name="dubbo" port="20880" />
<!-- 声明需要暴露的服务接口 ,ref指向服务真正的实现对象-->
<dubbo:service interface="com.atguigu.gmall.service.UserService" ref="userServiceImpl" />
<!-- 服务的实现,添加到容器中 -->
<bean id="userServiceImpl" class="com.atguigu.gmall.service.impl.UserServiceImpl" />
<!--监控中心配置-->
<dubbo:monitor protocol="registry" />
<!--或者使用这个直连<dubbo:monitor address="127.0.0.1:7070"></dubbo:monitor>-->
</beans>
main方法中:
public static void main( String[] args ) throws IOException { ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("provider.xml"); ioc.start(); System.in.read(); }
2.让服务消费者去注册中心订阅服务提供者的服务地址
<context:component-scan base-package="com.atguigu.gmall.service.impl"></context:component-scan> <dubbo:application name="order-service-consumer"></dubbo:application> <dubbo:registry address="zookeeper://127.0.0.1:2181"></dubbo:registry> <dubbo:reference id="userService" interface="com.atguigu.gmall.service.UserService"/>
这里注意一点消费者接收的服务id要与提供者所提供的id一致