问题背景:
集群环境下,每台机器都需要有一个queue,用来接收同一个exchange传递的消息。所以queue的申明使用了机器ip作为后缀,即:queue_name = xxxxxx_机器ip。
由于是集群环境,如果使用注解@RabbitListener就无法灵活的监听到各个队列,所以使用了SimpleMessageListenerContainer实现动态监听。
代码如下:
1.首先创建一个监听器
@Component
public class BrowserMsgMqListener implements ChannelAwareMessageListener {
@Autowired
private SocketIOService socketIOService;
@Override
public void onMessage(Message message, Channel channel) throws Exception {
try{
// TODO 消费消息
}catch (Exception e){
// TODO 异常处理
}finally {
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
}
}
}
2.MqConfig配置类中装载SimpleMessageListenerContainer
@Bean
public SimpleMessageListenerContainer simpleMessageListenerContainer(){
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
container.setConcurrentConsumers(1);
container.setMaxConcurrentConsumers(1);
container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
container.setQueueNames(String.format(MqConstant.message_center_queue_browser_msg, getServerAddress()));
container.setMessageListener(browserMsgMqListener);
return container;
}
private String getServerAddress(){
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
return UUID.randomUUID().toString();
}
}