今天我们讲解的重点有两个:
1.Config是如何对服务配置文件统一管理?
2.SpringCloudBus是如何实现修改后实时更新?
一.Spring Cloud Config
在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件。在Spring Cloud中,有分布式配置中心组件spring cloud config ,它支持配置服务放在配置服务的内存中(即本地),也支持放在远程Git仓库中。在spring cloud config 组件中,分两个角色,一是config server,二是config client。
1.先创建一个Config Server端
(1)先导入下面的依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
(2)在启动类中加入@EnableConfigServer注解开启配置服务器的功能
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
(3)在配置文件application.properties中配置
spring.application.name=config-server
server.port=8888
spring.cloud.config.server.git.uri:配置git仓库地址
spring.cloud.config.server.git.searchPaths:配置仓库路径
spring.cloud.config.label:配置仓库的分支
spring.cloud.config.server.git.username:访问git仓库的用户名
spring.cloud.config.server.git.password:访问git仓库的用户密码
2.创建一个Config client
(1)加入相关依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
(2)修改配置文件bootstrap.properties
spring.application.name=config-client
spring.cloud.config.label=
spring.cloud.config.profile=
spring.cloud.config.uri=
server.port=
(3)把剩下容易修改的参数都放在git或者github上的文件上
这样就实现了在git或者github中一次修改,可以有多个client的配置都进行了修改
二. Spring Cloud Bus
Spring Cloud Bus 将分布式的节点用轻量的消息代理连接起来。它可以用于广播配置文件的更改或者服务之间的通讯,也可以用于监控。这里要讲述的是用Spring Cloud Bus实现通知微服务架构的配置文件的更改
(1)在server和client端,都加入amqp的依赖(这里我们采用消息队列rabbitMQ来传递消息)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
(2)在配置文件application.properties中加上RabbitMq的配置,包括RabbitMq的地址、端口,用户名、密码。并需要加上spring.cloud.bus的三个配置,具体如下:(也可以配置在git上)
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.cloud.bus.enabled=true
spring.cloud.bus.trace.enabled=true
management.endpoints.web.exposure.include=bus-refresh
这些都是固定配置!
(3)在client端的启动类中加入@RefreshScope注解,重新启动
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@RestController
@RefreshScope
public class ConfigClientApplication {
/**
* http://localhost:8881/actuator/bus-refresh
*/
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class, args);
}
}
(4)先去申请一个内网穿透的账号,再在github上配置文件夹里的配置中的Webhooks中,加入经过内网穿透过的网址即可