消息队列之Headers交换类型
1、说明
Headers类型的exchange使用的比较少,它也是忽略routingKey的一种路由方式。是使用Headers来匹配的。Headers是一个键值对,可以定义成Hashtable。发送者在发送的时候定义一些键值对,接收者也可以再绑定时候传入一些键值对,两者匹配的话,则对应的队列就可以收到消息。匹配有两种方式all和any。这两种方式是在接收端必须要用键值"x-mactch"来定义。all代表定义的多个键值对都要满足,而any则代码只要满足一个就可以了。fanout,direct,topic exchange的routingKey都需要要字符串形式的,而headers exchange则没有这个要求,因为键值对的值可以是任何类型。
2、生产者
public class P {
private final static String EXCHANGE_NAME = "header-exchange";
private final static String QUEUE_NAME = "header-queue";
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
// 创建连接和频道
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
//声明转发器和类型headers
channel.exchangeDeclare(EXCHANGE_NAME, "headers",false,true,null);
channel.queueDeclare(QUEUE_NAME,false, false, true,null);
Map<String, Object> map = new Hashtable<String, Object>();
map.put("x-match", "any");//all any
map.put("aaa", "01234");
map.put("bbb", "56789");
// 为转发器指定队列,设置binding 绑定header键值对
channel.queueBind(QUEUE_NAME, EXCHANGE_NAME,"", map);
//声明转发器和类型headers
channel.exchangeDeclare(EXCHANGE_NAME, "headers",false,true,null);
String message = new Date().toLocaleString() + " : log something";
Map<String,Object> headers = new Hashtable<String, Object>();
headers.put("bbb", "56789");
Builder properties = new BasicProperties.Builder();
properties.headers(headers);
// 指定消息发送到的转发器,绑定键值对headers键值对
channel.basicPublish(EXCHANGE_NAME, "",properties.build(),message.getBytes());
System.out.println("Sent message :'" + message + "'");
channel.close();
connection.close();
}
}
3、消费者
public class C {
private final static String QUEUE_NAME = "header-queue";
public static void main(String[] args) throws Exception {
// 创建连接和频道
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
String msg = new String(body, "utf-8");
System.out.println(msg);
}
};
// 指定接收者,第二个参数为自动应答,无需手动应答
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}