总之,topics模型就是比direct模型多了一个通配符。
提供者
public class Provider {
public static void main(String
[] args
) throws IOException
{
Connection connection
= RabbitMqUtils
.getConnection();
Channel channel
= connection
.createChannel();
channel
.exchangeDeclare("topics","topic");
String routinkey
= "user.save";
channel
.basicPublish("topics",routinkey
,null
,("这个是路由key发送的消息").getBytes());
RabbitMqUtils
.closeConnectionAndChannel(channel
,connection
);
}
}
创建了一个topic类型的交换机,并且往这个交换机里面放了一个 加了路由键 的消息
消费者
public class Customer {
public static void main(String
[] args
) throws IOException
{
Connection connection
= RabbitMqUtils
.getConnection();
Channel channel
= connection
.createChannel();
channel
.exchangeDeclare("topics","topic");
String queue
= channel
.queueDeclare().getQueue();
channel
.queueBind(queue
,"topics","user.*");
channel
.basicConsume(queue
,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
));
}
});
}
}
在消费者里面绑定了交换机和队列,并这个队列里面是有通配符的路由键。
以后消费者在队列里面拿消息的时候,只可以拿这个路由键匹配的消息。