与 ActiveMQ 拿到消息就直接放在队列等待消费者拿走不同, Rabbit 拿到消息之后,会先交给 交换机 (Exchange), 然后交换机再根据预先设定的不同绑定( Bindings )策略,来确定要发给哪个队列。
RabbitMQ提供了四种Exchange模式:fanout,direct,topic,header
1.消费者
package com.touch.direct;
import cn.hutool.core.util.RandomUtil;
import com.rabbitmq.client.*;
import com.touch.utils.RabbitMQUtil;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Random;
import java.util.concurrent.TimeoutException;
public class TestDriectCustomer {
private final static String QUEUE_NAME = "direct_queue";
public static void main(String[] args) throws IOException, TimeoutException {
//为当前消费者取随机名
final String name = "consumer-"+RandomUtil.randomString(5);
RabbitMQUtil.checkServer();
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME,false,false,true,null);
System.out.println(name +" 等待接受消息");
//DefaultConsumer类实现了Consumer接口,通过传入一个频道,
// 告诉服务器我们需要那个频道的消息,如果频道中有消息,就会执行回调函数handleDelivery
Consumer consumer=new DefaultConsumer(channel){
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte[] body) throws UnsupportedEncodingException {
String message = new String (body,"UTF-8");
System.out.println(name + " 接收到消息 '" + message + "'");
}
};
//自动回复队列应答 -- RabbitMQ中的消息确认机制
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}
2.生产者
package com.touch.direct;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.touch.utils.RabbitMQUtil;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* 。
* 先启动两个消费者
* 再启动生产者,生产100条信息, 两个消费者分食100条信息 与ActiveMQ队列模式似
*/
public class TestDriectProducer {
public static final String QUEUE_NAME="direct_queue";
public static void main(String[] args) throws IOException, TimeoutException {
RabbitMQUtil.checkServer();
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置RabbitMQ相关信息
factory.setHost("localhost");
//创建一个新的连接
Connection connection = factory.newConnection();
//创建一个通道
Channel channel = connection.createChannel();
for(int i=0;i<100;i++){
String message = "direct 消息 " +i;
channel.basicPublish("",QUEUE_NAME,null,message.getBytes("UTF-8"));
System.out.println("发送消息:"+message);
}
channel.close();
connection.close();
}
}
[源代码地址:https://github.com/hyghub/javanotes]
[学 习 地 址:http://how2j.cn/k/message/message-rabbitmq-type/2031.html]