直接上代码
package com.demo.controller;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.demo.util.RabbitMQ;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
public class RabbitMQController {
//1、简单队列
//缺点:耦合性高,生产者一一对应消费者,如果想多个消费者消费队列中的消息,这时候就不行了。队列名变更,这时候要同时变更。
/**
* 生产者
* @throws IOException
* @throws TimeoutException
*/
public void sendMq() throws IOException, TimeoutException {
//创建连接
Connection connection=RabbitMQ.getConnection();
//得到通道
Channel channel =connection.createChannel();
//得到队列
channel.queueDeclare("queue1", false, false, false, null);
String msg="hello world";
channel.basicPublish("", "queue1", null, msg.getBytes());
channel.close();
connection.close();
}
/**
* 消费者
* @throws IOException
* @throws TimeoutException
*/
public void getMq() throws IOException, TimeoutException {
//创建连接
Connection connection=RabbitMQ.getConnection();
//得到通道
Channel channel =connection.createChannel();
//得到队列
channel.queueDeclare("queue1", false, false, false, null);
DefaultConsumer consumer=new DefaultConsumer(channel) {
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException {
String msg=new String(body);
System.out.println(msg);
};
};
channel.basicConsume("queue1", true, consumer);
}
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
RabbitMQController c=new RabbitMQController();
c.sendMq();
c.getMq();
}
}
简单队列只是简单的发一个去一个而已。
不足:耦合性高,生产者一一对应消费者,如果想多个消费者消费队列中的消息,这时候就不行了。队列名变更,这时候要同时变更。
网友评论