1. Dubbo简介
Dubbo是一款高性能、轻量级的开源Java RPC框架,可以和Spring框架无缝集成,它提供了三大核心能力:面向接口的远程方法调用,智能容错和负载均衡,以及服务自动注册和发现。
Dubbo的主要核心部件:
- Remoting:网络通信框架,实现了sync-over-async和request-response消息机制
- RPC:一个远程过程调用的抽象,支持负载均衡、容灾和集群功能
- Registry:服务目录框架用于服务的注册和服务事件发布和订阅
Dubbo官网:https://dubbo.apache.org/zh/
RPC(Remote Procedure Call,远程过程调用)在分布式系统中的系统环境建设和应用程序设计中的应用:
- 分布式操作系统的进程间通讯
- 构造分布式计算的软件环境
- 远程数据库服务
- 分布式应用程序设计
- 分布式程序的调试
RPC调用:Dubbo可以充当客户端存根和服务端存根
Dubbo依赖关系*:图中只包含RPC的层,不包含Remoting的层,Remoting整体都隐含在Protocol中;蓝色的表示与业务有交互,绿色的表示只对Dubbo内部交互
- Container:服务运行容器;负责启动、加载、运行服务提供者
- Provider:暴露服务的服务提供方;在启动时向注册中心注册自己提供的服务
- Consumer:调用远程服务的服务消费方;在启动时向注册中心订阅自己所需的服务
- Registry:服务注册与发现的注册中心;返回服务提供者地址列表给消费者,如果有变更,注册中心将基于长连接推送变更数据给消费者
- 服务消费者从提供者地址列表中,基于软负载均衡算法选一台提供者进行调用,如果调用失败,再选另一台调用
- Monitor:统计服务的调用次数和调用时间的监控中心;服务消费者和提供者在内存中累计调用次数和调用时间,定时每分钟发送一次统计数据到监控中心
- 可以使用ZooKeeper来充当注册中心
2. Dubbo基本使用*
示例:页面发送请求:user/findById.do?id=1根据id从数据库获取用户对象;使用Dubbo,完成服务消费者调用服务提供者的方法
2.1 创建父工程
不实现任何代码,完成依赖管理:
artifactId:dubbo_parent
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.webmvc.version>5.0.5.RELEASE</spring.webmvc.version>
<dubbo.version>2.6.2</dubbo.version>
<zookeeper.version>3.4.7</zookeeper.version>
<curator.verion>4.0.1</curator.verion>
<mybatis.version>3.4.5</mybatis.version>
<mysql.version>5.1.47</mysql.version>
<mybatis-spring.version>1.3.2</mybatis-spring.version>
<druid.version>1.1.9</druid.version>
<log.version>1.2.17</log.version>
<slf4j.version>1.7.25</slf4j.version>
</properties>
<dependencyManagement>
<dependencies>
<!--springmvc的环境-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.webmvc.version}</version>
</dependency>
<!--dubbo的环境-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>${dubbo.version}</version>
</dependency>
<!--zookeeper的环境-->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>${curator.verion}</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>${curator.verion}</version>
</dependency>
<!--mybatis的环境-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--spring的环境-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.webmvc.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.webmvc.version}</version>
</dependency>
<!--日志的环境-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.18</version>
</dependency>
</dependencies>
</dependencyManagement>
2.2 创建公共子模块
创建实体类:
artifactId:dubbo_common
<parent>
<artifactId>dubbo_parent</artifactId>
<groupId>com.52lhp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>dubbo_common</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
创建POJO:
package com.liu2m.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
private Integer id;
private String name;
private String password;
private Double balance;
}
2.3 创建接口子模块
接口子模块主要放业务接口的定义,它是服务消费者模块和服务提供者模块的公共依赖模块:
artifactId:dubbo_interface
<parent>
<artifactId>dubbo_parent</artifactId>
<groupId>com.52lhp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>dubbo_interface</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.52lhp</groupId>
<artifactId>dubbo_common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
定义业务接口:
package com.liu2m.service;
import com.liu2m.pojo.User;
public interface UserService {
User findById(int id);
}
2. 4 创建服务提供者子模块
服务提供者模块需要在容器启动时,把服务注册到zookeeper;对接口的实现,调用dao完成数据库的操作:
artifactId:dubbo_provider
<parent>
<artifactId>dubbo_parent</artifactId>
<groupId>com.52lhp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>dubbo_provider</artifactId>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>com.52lhp</groupId>
<artifactId>dubbo_interface</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
</dependencies>
创建UserDao接口:
package com.liu2m.dao;
import com.liu2m.pojo.User;
public interface UserDao {
User findById(Integer id);
}
创建UserDao接口的映射文件:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.liu2m.dao.UserDao">
<select id="findById" resultType="com.liu2m.pojo.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
创建UserServiceImpl实现类:
package com.liu2m.service;
import com.liu2m.dao.UserDao;
import com.liu2m.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Override
public User findById(int id) {
return userDao.findById(id);
}
}
创建Spring整合MyBatis的配置文件spring-dao.xml
创建Spring事务配置文件:spring-tx.xml
创建spring-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.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
<!--服务提供者的名称,需要唯一-->
<dubbo:application name="dubbo_provide"/>
<!--注册中心的地址:使用zookeeper-->
<dubbo:registry address="zookeeper://127.0.0.1:2181"/>
<!--超时时间设置为10秒-->
<dubbo:provider timeout="10000"/>
<!--发布的服务接口
使用interface调用服务,调用的是spring容器中实现类的方法-->
<dubbo:service interface="com.liu2m.service.UserService" ref="userService"/>
<!--注入Service:服务真正的执行者-->
<bean id="userService" class="com.liu2m.service.UserServiceImpl"/>
<!--导入spring-tx.xml-->
<import resource="classpath:spring-tx.xml"/>
</beans>
启动Zookeeper
启动项目:只要能启动spring的容器(加载spring的配置文件)就可以启动项目,因此有3种方式:
-
方式1:用程序加载spring-provider.xml
package com.liu2m; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.io.IOException; public class ProviderApplication { public static void main(String[] args) throws IOException { new ClassPathXmlApplicationContext("classpath:spring-provider.xml"); System.in.read(); } }
-
方式2:在web.xml中使用监听器
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!--加载spring-provider.xml--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-provider.xml</param-value> </context-param> <!--监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
方式3:在web.xml中使用DispatcherServlet
2.5 创建服务消费者子模块
在Dubbo中,服务端抛出自定义异常时,要在接口方法中声明,否则会被Dubbo转成RuntimeException
服务消费者模块需要在容器启动时去注册中心订阅服务;引用接口,接收参数调用服务,返回结果
artifactId:double_consumer
<parent>
<artifactId>dubbo_parent</artifactId>
<groupId>com.52lhp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>double_consumer</artifactId>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>com.52lhp</groupId>
<artifactId>dubbo_interface</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
</dependency>
</dependencies>
创建UserController:
package com.liu2m.controller;
import com.liu2m.pojo.User;
import com.liu2m.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findById")
public User findById(int id) {
// 调用服务,返回JSON
return userService.findById(id);
}
}
创建spring-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"
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">
<!--服务消费者的名称,需要唯一-->
<dubbo:application name="dubbo_consumer"/>
<!--注册中心的地址:使用zookeeper-->
<dubbo:registry address="zookeeper://127.0.0.1:2181"/>
<!--订阅的服务接口
服务提供者在注册中心注册的节点是接口,因此应该监听这个节点
接口调用时使用jdk动态代理,注册到spring容器中,id就是代理对象的id
id的值必须与controller中的@autowired的属性名称要一致-->
<dubbo:reference interface="com.liu2m.service.UserService" id="userService"/>
<!--需要配置在服务消费者一方
check:启动时是否检查服务提供者是否存在,默认为true
timeout:超时调用,dubbo调用的时间默认为1秒,如果超过调用的时间就会报错
retries:失败后的重试次数-->
<dubbo:consumer check="false" timeout="10000" retries="2"/>
</beans>
创建spring-mvc.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫controller-->
<context:component-scan base-package="com.liu2m.controller"></context:component-scan>
<!--注解驱动-->
<mvc:annotation-driven/>
<!--导入dubbo配置文件-->
<import resource="classpath:spring-consumer.xml"/>
</beans>
启动zookeeper
在web.xml中配置DispatcherServlet,然后启动Tomcat
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!--解决post请求的乱码过滤器-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3. Dubbo监控中心
启动zookeeper,若8080与zookeeper端口冲突,则会一闪而过,可以修改Tomcat端口
将dubbo-admin.war放到Tomcat的webapps下
-
启动Tomcat后dubbo-admin.war会自动解压,修改WEB-INF下的dubbo.properties:
# 当前使用的ZooKeeper的ip和端口 dubbo.registry.address=zookeeper://localhost:2181 # root用户的密码 dubbo.admin.root.password=root # guest用户的密码 dubbo.admin.guest.password=guest
重启Tomcat,访问http://localhost:8088/dubbo-admin/,输入用户名和密码
启动服务提供者子模块或服务消费者子模块后,可以在服务治理-->服务中可视化查看
4. Dubbo相关配置
4.1 注解实现服务提供者
-
在spring-provider.xml中配置包扫描
<dubbo:annotation package="com.liu2m.service"/>
-
去掉spring-provider.xml中的以下配置:
<!--发布的服务接口 使用interface调用服务,调用的是spring容器中实现类的方法--> <dubbo:service interface="com.liu2m.service.UserService" ref="userService"/> <!--注入Service:服务真正的执行者--> <bean id="userService" class="com.liu2m.service.UserServiceImpl"/>
在服务提供者的接口实现类上添加com.alibaba.dubbo.config.annotation.Service注解
4.2 注解实现服务提供者
-
在spring-consumer.xml中配置包扫描
<dubbo:annotation package="com.liu2m.service"/>
-
去掉spring-consumer.xml中的以下配置:
<!--订阅的服务接口 服务提供者在注册中心注册的节点是接口,因此应该监听这个节点 接口调用时使用jdk动态代理,注册到spring容器中,id就是代理对象的id id的值必须与controller中的@autowired的属性名称要一致--> <dubbo:reference interface="com.liu2m.service.UserService" id="userService"/>
把Controller类的UserService上的注解Autowired换成com.alibaba.dubbo.config.annotation.Reference注解
4.3 服务接口访问协议
<!--一般在服务提供者配置,可以在同一个工程中配置多个协议,不同服务可以使用不同的协议
name:协议名称,dubbo、rmi、hessian、http、webservice、rest、redis等
port:协议使用的端口号-->
<dubbo:protocol name="dubbo" port="20880"/>
<dubbo:protocol name="rmi" port="1099"/>
dubbo协议:默认端口20880
- 连接个数:单连接
- 连接方式:长连接
- 传输协议:TCP
- 传输方式:NIO异步传输
- 序列化:Hessian二进制序列化
- 适用范围:传入传出参数数据包较小(建议小于100K),消费者比提供者个数多,单一消费者无法压满提供者,尽量不要用dubbo协议传输大文件或超大字符串
rmi协议:
- 连接个数:多连接
- 连接方式:短连接
- 传输协议:TCP
- 传输方式:同步传输
- 序列化:Java标准二进制序列化
- 适用范围:传入传出参数数据包大小混合,消费者与提供者个数差不多,可传文件
Dubbo各种协议详解参考:https://www.cnblogs.com/duanxz/p/3555876.html
4.4 负载均衡*
Dubbo提供了多种均衡策略,如:随机random(默认)、轮询roundrobin、最少活跃数leastactive、一致哈希consistenhash
配置负载均衡策略,两者取一:
- 服务提供者:@Service(loadbalance = "roundrobin")
- 服务消费者:@Reference(loadbalance = "roundrobin")
5. 配合Dubbo实现ZooKeeper配置中心
-
把配置信息存入zookeeper(创建节点数据)
create /config config create /config/jdbc.driver 'com.mysql.jdbc.Driver' create /config/jdbc.url 'jdbc:mysql://localhost:3306/db01?useSSL=false' create /config/jdbc.username 'root' create /config/jdbc.password '123456'
-
在dubbo_common子模块中导入坐标
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-framework</artifactId> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency>
-
启动时从zookeeper读取配置信息并监听zookeeper中的配置信息目录:在dubbo_common子模块中创建一个类,继承PropertyPlaceholderConfigurer类重写processProperties方法,实现ApplicationContextAware接口重写setApplicationContext方法
package com.liu2m.utils; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.cache.TreeCache; import org.apache.curator.framework.recipes.cache.TreeCacheEvent; import org.apache.curator.framework.recipes.cache.TreeCacheListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.support.AbstractApplicationContext; import java.util.Properties; public class SettingCenterUtils extends PropertyPlaceholderConfigurer implements ApplicationContextAware { private CuratorFramework zookeeperClient; private AbstractApplicationContext applicationContext; private boolean first = true; public SettingCenterUtils() { // 创建zookeeper客户端并启动 String connectString = "127.0.0.1:2181"; int sessionTimeoutMs = 1000; int connectionTimeoutMs = 1000; RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 1); zookeeperClient = CuratorFrameworkFactory.newClient(connectString, sessionTimeoutMs, connectionTimeoutMs, retryPolicy); zookeeperClient.start(); } /** * 重写processProperties方法 * 相当于<context:property-placeholder location="classpath:jdbc.properties"/>标签 */ @Override protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { // 加载zookeeper配置信息 loadZk(props); if (first) { // 保证添加监听的方法只执行一次 // 监听zookeeper中的配置信息目录 addWatch(); first = false; } super.processProperties(beanFactoryToProcess, props); } // 重写设置ApplicationContext的方法 @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // AbstractApplicationContext父类提供了refresh方法,可以刷新spring容器中的对象,因此强转 this.applicationContext = (AbstractApplicationContext) applicationContext; } // 读取zookeeper中的配置 private void loadZk(Properties props) { try { // 读取配置信息 String driver = new String(zookeeperClient.getData().forPath("/config/jdbc.driver")); String url = new String(zookeeperClient.getData().forPath("/config/jdbc.url")); String username = new String(zookeeperClient.getData().forPath("/config/jdbc.username")); String password = new String(zookeeperClient.getData().forPath("/config/jdbc.password")); // 将配置信息设置到Properties中 props.setProperty("jdbc.driver", driver); props.setProperty("jdbc.url", url); props.setProperty("jdbc.username", username); props.setProperty("jdbc.password", password); } catch (Exception e) { e.printStackTrace(); } } /** * 监听zookeeper中的配置信息目录: * 1. 不要关闭client,否则无法进行监控 * 2. 修改完成后必须刷新spring容器中的对象 */ private void addWatch() { TreeCache treeCache = new TreeCache(zookeeperClient, "/config"); try { // 开始缓存 treeCache.start(); // 添加监听对象 treeCache.getListenable().addListener(new TreeCacheListener() { @Override public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { // 如果修改了配置,则zookeeper进行通知,重新读取配置信息,刷新spring容器 if (event.getType() == TreeCacheEvent.Type.NODE_UPDATED) { // 打印修改的结点,便于查看 System.out.println("path = " + event.getData().getPath() + ", data = " + new String(event.getData().getData())); // 刷新spring容器中的对象 // 刷新时会执行一次processProperties方法,可以重新读取zookeeper中的配置信息 applicationContext.refresh(); } } }); } catch (Exception e) { e.printStackTrace(); } } }
-
修改dubbo_provider子模块的spring-dao.xml,去掉引入jdbc配置文件的标签,然后对PropertyPlaceholderConfigurer的子类进行IoC:
<!--引入jdbc的properties配置文件,properties配置文件中的key一定要是带点分隔的--> <!--<context:property-placeholder location="classpath:jdbc.properties"/>--> <bean class="com.liu2m.utils.SettingCenterUtils"></bean>
启动服务提供者和服务消费者,在zookeeper中修改配置信息测试(建议创建两个数据库,然后修改url)