练习步骤:
1、安装zookeeper,以及ZooInspector
注:zookeeper是注册中心,ZooInspector 相当于zookeeper的客户端,可以查看注册上去的节点信息
2、创建生产者接口项目以及底层实现层项目(因为生产者只会给消费者暴露接口,并不会展示实际底层源码)
3、创建消费者项目
4、启动zookeeper
5、启动生产者底层实现项目
6、启动消费者项目
例子:
一、 生产者接口项目
idea中创建一个module,写一个简单的会员接口
二、生产者底层实现
pom文件导入接口项目,以及dubbo和zk的jar包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sunj.example</groupId>
<artifactId>customer-service</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>sunj.example</groupId>
<artifactId>customer-interfaces</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.5.6</version>
</dependency>
<!-- 添加zk客户端依赖 -->
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>
</dependencies>
</project>
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://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd ">
<!-- 提供方应用信息,用于计算依赖关系 -->
<dubbo:application name="provider" />
<!-- 使用zookeeper注册中心暴露服务地址 -->
<dubbo:registry address="zookeeper://127.0.0.1:2181" />
<!-- 用dubbo协议在29014端口暴露服务 -->
<dubbo:protocol name="dubbo" port="29014" />
<!-- 声明需要暴露的服务接口 -->
<dubbo:service interface="com.lala.service.UserService"
ref="userService" />
<!-- 具体的实现bean -->
<bean id="userService" class="com.lala.service.impl.UserServiceImpl" />
</beans>
三、消费者项目
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://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<!-- 消费方应用名,用于计算依赖关系,不是匹配条件,不要与提供方一样 -->
<dubbo:application name="consumer" />
<!-- 使用multicast广播注册中心暴露发现服务地址 -->
<dubbo:registry protocol="zookeeper" address="zookeeper://127.0.0.1:2181" />
<!-- 生成远程服务代理,可以和本地bean一样使用demoService -->
<dubbo:reference id="userService" interface="com.lala.service.UserService" />
</beans>
四、启动zookeeper
五、启动生产者项目
六、启动消费者
当消费者调用生产者时,生产者会做出反应
刷新zookeeper客户端,会发现多了消费者节点
一旦任何一个生产者和消费者服务挂掉,刷新zookeeper客户端,发现节点消失
悟:
1、provider.xml和consumer.xml 文件,即生产者和消费者配置文件中配置相同的zookeeper,也就是同一个注册中心,生产者把自己注册上去,消费者也注册上去,两者就可以远程访问对方
2、System.in.read(); 该行代码等待输入,可以模拟服务一直处于服务状态