SpringCloud(二):消息总线与配置中心

SpringCloud(二):配置中心与消息总线
简介:
在分布式系统架构中,通常会使用中间件来作为消息代理实现一个共用的消息系统。
分布式中的其他服务都连接到消息系统,并且实现消息的生产、监听、和消费,
我们把这样的消息系统称为消息总线。
在消息总线上的每个实例都可以广播一些消息让其他实例接收到,比如我们之前实现的
配置中心,我们使用WebHooks来推送一个post请求去refresh客户端实现刷新配置,
这样的方式其实很不合理,在有多个客户端的情况下,就需要逐个刷新,虽然可以专门
使用一个客户端来做刷新其他客户端的操作,但是这样违反了单一职责。
通过使用 Spring Cloud Bus 可以比较容易的搭建消息总线系统,在使用之前我们需要先了解
消息代理,消息代理(Message Broker)是一种消息验证、传输、路由的架构模式。消息代理可以减小应用之前相互依赖,通过消息通信解耦系统之前的直接调用。
消息代理是一个中间件产品,他的核心是一个消息的路由程序。目前有很多消息代理的开源产品,比如RabbitMQ,Kafka,ActiveMQ等。SpringCloud目前只支持RabbitMQ和Kafka,SpringCloud包含了对RabbitMQ的自动化配置,所以我们使用 RabbitMQ来整合SpringCloudBus实现消息总线。
功能介绍图
在这里插入图片描述
调用说明:
1.启动服务注册中心
2.启动服务提供者和服务消费者,并且都将自己注册到服务注册中心
3.服务消费者从服务注册中心获取注册中心的服务信息(获取服务提供者地址给消费者)
4.服务消费者调用服务提供者的服务

2.代码示例
pom.xml引入jar包

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-bus-amqp</artifactId>
    </dependency>
</dependencies>

这个依赖引用的各个组件的功能说明
config-server 是一个配置管理服务器,可用来创建配置管理中心
eureka 是一个服务注册和发现的工具组件,提供了注册管理中心客户端的功能
bus-amqp 是一个消息纵向服务组件,可以可以提供管理中心提供使用消息进行通信的功能

创建一个启动类 代码如下
@SpringBootApplication
@EnableConfigServer //配置管理服务器
@EnableDiscoveryClient //注册到管理中心的客户端
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
然后在工程配置文件中
bootstrap.yml
spring:
application:
name: config

cloud:
config:
server:
git:
uri: https://gitee.com/luzhuhong/base-config-repo.git
username:
password:

rabbitmq:
  addresses: amqp://47.98.133.78:5672
  username: guest
  password: guest

application.yml
server:
port: 8888

eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/

management.security.enabled: false

cloud:
sample:
msg: hello
简单的配置中心搭建完成
更新所有客户端的配置 可以用如下命令
curl -X POST http://localhost:8888/bus/refresh
进行单个服务的更新的命令
curl -X POST http://localhost:8888/bus/refresh?destination=orderweb:**
需要其他客户端能使用 需要配置@RefreshScope 才能生效

猜你喜欢

转载自blog.csdn.net/luzhuhong1/article/details/82798924