引人依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
配置rabbit参数
rabbitmq:
host: 172.21.126.136
port: 5672
username: cares
password: Cares123
定义事件
package com.cares.fids.server.events;
import org.springframework.cloud.bus.event.RemoteApplicationEvent;
/**
* @author wangcj
* @desc
* @date 2021/1/5 14:25
**/
public class FidsCmdRequestRemoteEvent extends RemoteApplicationEvent {
public FidsCmdRequestRemoteEvent() {
}
public FidsCmdRequestRemoteEvent(Object source, String originService) {
super(source, originService);
}
}
发布事件
@Resource
private BusProperties busProperties;
@Resource
private ApplicationContext applicationContext;
FidsCmdRequestRemoteEvent event = new FidsCmdRequestRemoteEvent(baseMsg, busProperties.getId());
applicationContext.publishEvent(event);
监听事件
@EventListener
public void sendRequest(FidsCmdRequestRemoteEvent event) {
BaseMsg msg = (BaseMsg) event.getSource();
log.info("收到广播消息{},mac={}", msg.getType(), msg.getClientId());
Channel channel = clientConnectionMap.getClientChannelBytoken(msg.getClientId());
if (null != channel) {
channel.writeAndFlush(msg);
}
}
总结
发布事件时,本机serviceid要使用 busProperties.getId(),否则消息发不到其他微服务上
本文构造函数表示发送所有微服务
在需要微服务之间协调时,spring cloud bus将会很方便
比如微服务开启socket服务,前端通过socket服务向指定的socket客户端发送指令
那么前端请求到达微服务后,将请求广播,指定的socket的客户端连接到哪个微服务,哪个微服务就处理
本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!