Topic类型的交换机与direct相比,都是可以根据routingkey把消息路由到不同的队列,只不过Topic类型交换机可以让队列绑定的Routingkey的时候使用通配符,这种模型ROutingkey 一般都是由一个或者多个单词组成,多个单词之间以 "."分割
package com.baizhi.Topics;
import com.baizhi.Utils.rabbitmqUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
public class Provider {
public static void main(String[] args) {
Connection connection= rabbitmqUtils.getConnection();
try {
Channel channel=connection.createChannel();
channel.exchangeDeclare("topics", "topic");
String routeKey="user.save";
channel.basicPublish("topics", routeKey, null, ("这是topic模型发布的消息,它的routingkey是"+routeKey).getBytes());
rabbitmqUtils.closeChannlAndConnection(channel, connection);
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.baizhi.Topics;
import com.baizhi.Utils.rabbitmqUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Customer {
public static void main(String[] args) {
Connection connection= rabbitmqUtils.getConnection();
try {
Channel channel=connection.createChannel();
//绑定交换机,创建队列,绑定交换机和队列
channel.exchangeDeclare("topics", "topic");
String queueName=channel.queueDeclare().getQueue();
String routeKey="user.*";
channel.queueBind(queueName, "topics", routeKey);
channel.basicConsume(queueName, true, new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者1"+new String(body));
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.baizhi.Topics;
import com.baizhi.Utils.rabbitmqUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Customer1 {
public static void main(String[] args) {
Connection connection= rabbitmqUtils.getConnection();
try {
Channel channel=connection.createChannel();
//绑定交换机,创建队列,绑定交换机和队列
channel.exchangeDeclare("topics", "topic");
String queueName=channel.queueDeclare().getQueue();
String routeKey="user.#";
channel.queueBind(queueName, "topics", routeKey);
channel.basicConsume(queueName, true, new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者1"+new String(body));
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试代码,当routekey为user.save,消费者1,2 都能接受。
当routekey为user.save.delete,消费者1不能接受,消费者2可以接收