java操作RabbitMQ。生产者、消费者。
jar下载地址: http://central.maven.org/maven2/com/rabbitmq/amqp-client/3.6.5/amqp-client-3.6.5.jar
package mq;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* @author flysLi
* @ClassName RabbitMqProductor
* @Decription TODO
* @Date 2019/1/24 14:58
* @Version 1.0
*/
public class RabbitMqProductor {
public final static String QUEUE_NAME = "rabbitMQ_flysLi";
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
//创建一个链接
final Connection connection = factory.newConnection();
//创建一个通道
Channel channel = connection.createChannel();
//声明一个队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
//发送消息到队列
String message = "Hello RabbitMQ2";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
System.out.println("Producer Send +'" + message + "'");
//关闭通道和连接
channel.close();
connection.close();
}
}
package mq;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeoutException;
/**
* @author flysLi
* @ClassName RabbitMqConsumer
* @Decription TODO
* @Date 2019/1/24 15:10
* @Version 1.0
*/
public class RabbitMqConsumer {
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(RabbitMqProductor.QUEUE_NAME, false, false, false, null);
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] bytes) throws UnsupportedEncodingException {
String message = new String(bytes, "UTF-8");
System.out.println("消息受理:" + message);
}
};
/*自动回复队列应答(rabbitMQ中的消息确认机制)*/
channel.basicConsume(RabbitMqProductor.QUEUE_NAME, true, consumer);
}
}