Java tutorial
/* * Copyright (c) 2001-2018 GuaHao.com Corporation Limited. All rights reserved. * This software is the confidential and proprietary information of GuaHao Company. * ("Confidential Information"). * You shall not disclose such Confidential Information and shall use it only * in accordance with the terms of the license agreement you entered into with GuaHao.com. */ package com.github.hexsmith.rabbitmq.consumer; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Consumer; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; import java.io.IOException; import java.util.concurrent.TimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ? * * @author yuzp * @version V1.0 * @since 2018-06-14 16:46 */ public class MultiMessageConsumer { private static final Logger logger = LoggerFactory.getLogger(MultiMessageConsumer.class); public boolean consume(String queueName, String consumerName) { //RabbitMQ ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.1"); Connection connection = null; Channel channel = null; try { connection = factory.newConnection(); channel = connection.createChannel(); //queue??queue //?queueDeclare???queue channel.queueDeclare(queueName, false, false, false, null); //?DefaultConsumerhandleDelivery???getByte()???String Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); logger.info("[{}]" + "Received '" + message + "'", consumerName); } }; //?? channel.basicConsume(queueName, true, consumer); //???rabbitMQ } catch (IOException | TimeoutException e) { //?false logger.error("send message failed!", e); return false; } return true; } }