SpringBoot集成SpringCloud-Config实现DataSource热部署

今天,日月在这里教大家如何使用配置中心实现dataSource热部署。所谓热部署,简单的说就是在不重启服务的情况下修改数据源的配置。
配置中心我们采用 SpringCloud配置中心–svn(五)配置中心和消息总线这一章的工程

我们继续在上一章 Spring Boot 集成 Mybatis 实现 Druid 多数据源 上进行修改

1、添加配置中心依赖



    org.springframework.cloud
    spring-cloud-starter-config




    org.springframework.cloud
    spring-cloud-starter-eureka




    org.springframework.cloud
    spring-cloud-starter-bus-amqp

2、添加配置中心配置

application.properties

spring.application.name=springboot
server.port=8002
#刷新时,关闭安全验证
management.security.enabled=false
#开启消息跟踪
spring.cloud.bus.trace.enabled=true
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
 
bootstrap.properties 
spring.cloud.config.name=springboot-config
spring.cloud.config.profile=dev
spring.cloud.config.label=springboot
#开启Config服务发现支持
spring.cloud.config.discovery.enabled=true 
#指定server端的name,也就是server端spring.application.name的值
spring.cloud.config.discovery.serviceId=spring-cloud-config-server
#指向配置中心的地址
eureka.client.serviceUrl.defaultZone=http://localhost:8080/eureka/

3、将数据源的配置移至配置中心目录
SpringBoot集成SpringCloud-Config实现DataSource热部署_第1张图片

这里我们首先连接test1和test2数据库

4、修改启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class SpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

5、 在两个数据源的配置类中添加 @RefreshScope 注解
SpringBoot集成SpringCloud-Config实现DataSource热部署_第2张图片

这样我们就修改好了,启动项目,访问http://localhost:8002/hello
返回:
SpringBoot集成SpringCloud-Config实现DataSource热部署_第3张图片
说明我们成功的将数据源的配置移动到了配置中心进行管理

6、新建test3和test4数据库并新建test表
SpringBoot集成SpringCloud-Config实现DataSource热部署_第4张图片

7、修改配置中心的数据源配置
将连接test1和test2数据库修改为连接test3和test4数据库并提交svn
SpringBoot集成SpringCloud-Config实现DataSource热部署_第5张图片
8、向配置中心发送配置刷新请求
SpringBoot集成SpringCloud-Config实现DataSource热部署_第6张图片
9、刷新客户端浏览器页面
SpringBoot集成SpringCloud-Config实现DataSource热部署_第7张图片
可以看到,数据读取成功的从test1和test2数据库转移到了test3和test4数据库,至此,就实现了dataSource
的热部署

你可能感兴趣的:(springCloud,spring,boot,系列)