电子商务平台源码请加企鹅求求:三五三六二四七二五九。spring cloud是按照spring的配置对一系列微服务框架的集成,spring cloud bus是其中一个微服务框架,用于实现微服务之间的通讯。java
spring cloud bus整合 java的事件处理机制和消息中间件消息的发送和接受,主要由发送端、接收端和事件组成。针对不一样的业务需求,能够设置不一样的事件,发送端发送事件,接收端接受相应的事件,并进行相应的处理。spring
二、原理json
spring cloud bus整合了java的事件处理机制和消息中间件,因此下面就从这两个方面来讲明spring cloud bus的原理。 bootstrap
如图所示,做以下解释:bash
(1)完整流程:发送端(endpoint)构造事件event,将其publish到context上下文中(spring cloud bus有一个父上下文,bootstrap),而后将事件发送到channel中(json串message),接收端从channel中获取到message,将message转为事件event(转换过程这一块没有深究),而后将event事件publish到context上下文中,最后接收端(Listener)收到event,调用服务进行处理。整个流程中,只有发送/接收端从context上下文中取事件和发送事件是须要咱们在代码中明确写出来的,其它部分都由框架封装完成。app
(2)先大体描述了一下流程,关于封装的部分流程,咱们基本上能够在BusAutoConfiguration.class中找到,下面的代码都是这个类中的代码框架
  @EventListener(classes = RemoteApplicationEvent.class)
public void acceptLocal(RemoteApplicationEvent event) {
if (this.serviceMatcher.isFromSelf(event)
&& !(event instanceof AckRemoteApplicationEvent)) {
this.cloudBusOutboundChannel.send(MessageBuilder.withPayload(event).build());
}
}
复制代码
这是封装了java事件处理机制,当收到RemoteApplicationEvent时,若是这个event是从这个服务发出的,并且不是ack事件,那么就会把这个事件发送到channel中。微服务
  @StreamListener(SpringCloudBusClient.INPUT)
public void acceptRemote(RemoteApplicationEvent event) {
if (event instanceof AckRemoteApplicationEvent) {
if (this.bus.getTrace().isEnabled() && !this.serviceMatcher.isFromSelf(event)
&& this.applicationEventPublisher != null) {
this.applicationEventPublisher.publishEvent(event);
}
// If it's an ACK we are finished processing at this point return; } if (this.serviceMatcher.isForSelf(event) && this.applicationEventPublisher != null) { if (!this.serviceMatcher.isFromSelf(event)) { this.applicationEventPublisher.publishEvent(event); } if (this.bus.getAck().isEnabled()) { AckRemoteApplicationEvent ack = new AckRemoteApplicationEvent(this, this.serviceMatcher.getServiceId(), this.bus.getAck().getDestinationService(), event.getDestinationService(), event.getId(), event.getClass()); this.cloudBusOutboundChannel .send(MessageBuilder.withPayload(ack).build()); this.applicationEventPublisher.publishEvent(ack); } } if (this.bus.getTrace().isEnabled() && this.applicationEventPublisher != null) { // We are set to register sent events so publish it for local consumption, // irrespective of the origin this.applicationEventPublisher.publishEvent(new SentApplicationEvent(this, event.getOriginService(), event.getDestinationService(), event.getId(), event.getClass())); } } 复制代码
@StreamListener这个标签有兴趣的能够去了解一下。这个方法就是从channel中取出事件进行处理的过程(message转事件部分须要自行了解,我没有深刻研究),根据事件的类型、发送方和接收方来处理这个事件:若是是ack事件,发送到context上下文中;若是本身是接收端且不是发送端,就会将事件发送到context上下文。ui
(3)消息中间件能够采用rabbitmq、kafka之类的。this