【SpringCloud】这一次终于使用MQ解决了Eureka服务下线延迟感知问题
@Component
public class EurekaEventToRabbitMQPublisher {
private static final Logger LOGGER = LoggerFactory.Logger(EurekaEventToRabbitMQPublisher.class);
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private Environment environment;
@Autowired
private DiscoveryClient discoveryClient;
@RabbitListener(queues = "#{T(com.netflix.appinfo.InstanceInfo).InstanceStatus.DOWN}")
public void handleInstancesChangeEvent(Message message) {
try {
InstanceInfo instanceInfo = objectMapper.readValue(new String((byte[]) message.getPayload()), InstanceInfo.class);
String serviceId = instanceInfo.getAppName();
List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
if (instances.isEmpty()) {
rabbitTemplate.convertAndSend(environment.getProperty("spring.rabbitmq.exchange"),
serviceId, instanceInfo.getAppName());
}
} catch (Exception e) {
LOGGER.error("处理Eureka服务下线事件异常:", e);
}
}
}
这段代码示例展示了如何使用RabbitMQ来替代Eureka的服务下线延迟感知问题。通过定义一个RabbitMQ的监听器来处理服务下线事件,并且只有在服务实例列表为空时,才发送一个消息到RabbitMQ交换器。这样就可以避免Eureka服务器的下线延迟问题,实现即时的服务状态感知。
评论已关闭