packagelogs;importjava.io.IOException;importjava.util.concurrent.TimeoutException;importcom.rabbitmq.client.Channel;importcom.rabbitmq.client.Connection;importcom.rabbitmq.client.DefaultConsumer;importcom.rabbitmq.client.Envelope;importcom.rabbitmq.client.AMQP.BasicProperties;importutils.ChannelUtils;public classListenerRabbitMQLogs {private static final String QUEUE_NAME_DEBUG = "queue_debug";private static final String QUEUE_NAME_INFO = "queue_info";private static final String QUEUE_NAME_WARNING = "queue_warning";private static final String QUEUE_NAME_ERROR = "queue_error";private static final String EXCHANGE_NAME_LOG = "amq.rabbitmq.log";public static void main(String[] args) throwsIOException, TimeoutException {
Connection connection= ChannelUtils.getConnection("ListenerLog");
Channel channelDebug=connection.createChannel();
Channel channelInfo=connection.createChannel();
Channel channelWarning=connection.createChannel();
Channel channelError=connection.createChannel();
channelDebug.queueDelete(QUEUE_NAME_DEBUG);
channelDebug.queueDeclare(QUEUE_NAME_DEBUG,false, false, false, null);
channelInfo.queueDelete(QUEUE_NAME_INFO);
channelInfo.queueDeclare(QUEUE_NAME_INFO,false, false, false, null);
channelWarning.queueDelete(QUEUE_NAME_WARNING);
channelWarning.queueDeclare(QUEUE_NAME_WARNING,false, false, false, null);
channelError.queueDelete(QUEUE_NAME_ERROR);
channelError.queueDeclare(QUEUE_NAME_ERROR,false, false, false, null);
channelDebug.queueBind(QUEUE_NAME_DEBUG, EXCHANGE_NAME_LOG,"debug");
channelInfo.queueBind(QUEUE_NAME_INFO, EXCHANGE_NAME_LOG,"info");
channelWarning.queueBind(QUEUE_NAME_WARNING, EXCHANGE_NAME_LOG,"warning");
channelError.queueBind(QUEUE_NAME_ERROR, EXCHANGE_NAME_LOG,"error");
channelDebug.basicConsume(QUEUE_NAME_DEBUG,new LogsConsumer(channelDebug,"Debug"));
channelInfo.basicConsume(QUEUE_NAME_INFO,new LogsConsumer(channelInfo,"Info"));
channelWarning.basicConsume(QUEUE_NAME_WARNING,new LogsConsumer(channelWarning,"Warning"));
channelError.basicConsume(QUEUE_NAME_ERROR,new LogsConsumer(channelError,"Error"));
}
}class LogsConsumer extendsDefaultConsumer {privateString logLevel;publicLogsConsumer(Channel channel,String logLevel) {super(channel);this.logLevel =logLevel;
}
@Overridepublic void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)throwsIOException {
System.out.println(logLevel+":"+newString(body));//使用手动确认模式,这里需要确认收到消息。
getChannel().basicAck(envelope.getDeliveryTag(), false);
}
}