总之,topics模型就是比direct模型多了一个通配符。

提供者

public class Provider {
   

    public static void main(String[] args) throws IOException {
   
        Connection connection = RabbitMqUtils.getConnection();
        // 创建通道
        Channel channel = connection.createChannel();
// 将通道声明指定的交换机 参数1:交换机的名称 参数2:交换机的类型
        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();
        // 将通道声明指定的交换机 参数1:交换机的名称 参数2:交换机的类型 fanout 广播类型
        channel.exchangeDeclare("topics","topic");
// 创建临时队列
        String queue = channel.queueDeclare().getQueue();
// 绑定交换机和队列,意思是交换机里面信息有error这个路由,队列里面也有这个error路由,消费者才可以消费
        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));
            }
        });
    }
}

在消费者里面绑定了交换机和队列,并这个队列里面是有通配符的路由键。

以后消费者在队列里面拿消息的时候,只可以拿这个路由键匹配的消息。