spring CloudBus 将分布式的节点和轻量的消息代理链接起来。这能够用于广播配置文件的更改或者其余的管理工做。一个关键的思想就是,消息总线能够为微服务作监控,也能够做为应用程序之间相互通信。须要JAVA Spring Cloud大型企业分布式微服务云构建的B2B2C电子商务平台源码 一零三八七七四六二六web
1、准备工做spring
本文仍是基于上一篇文章来实现。按照官方文档,咱们只须要在配置文件中配置 spring-cloud-starter-bus-amqp ;这就是说咱们须要装rabbitMq,点击rabbitmq下载。至于怎么使用 rabbitmq,搜索引擎下。浏览器
2、改造config-clientapp
在pom文件加入spring-cloud-starter-bus-amqp,完整的配置文件以下:分布式
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bus-amqp</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
在配置文件application.properties中加上RabbitMq的配置,包括RabbitMq的地址、端口,用户名、密码。并须要加上spring.cloud.bus的三个配置,具体以下:spring-boot
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
ConfigClientApplication启动类代码以下:微服务
@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); } @Value("${foo}") String foo; @RequestMapping(value = "/hi") public String hi(){ return foo; }}
依次启动eureka-server、confg-cserver,启动两个config-client,端口为:888一、8882。post
访问http://localhost:8881/hi 或者 http://localhost:8882/hi 浏览器显示:foo version 3搜索引擎
这时咱们去代码仓库将foo的值改成“foo version 4”,即改变配置文件foo的值。若是是传统的作法,须要重启服务,才能达到配置文件的更新。此时,咱们只须要发送post请求:http://localhost:8881/actuator/bus-refresh, 你会发现config-client会从新读取配置文件,这时咱们再访问http://localhost:8881/hi 或者http://localhost:8882/hi ,浏览器显示:foo version 4代理
另外,/bus/refresh接口能够指定服务,即便用”destination”参数,好比 “/bus/refresh?destination=customers:” 即刷新服务名为customers的全部服务。