rabbitmq随笔

一、rabbitmq的各参数释义

1、durable:是否保留在服务中,true表示重启不会删除

2、exclusive :是否独占,true表示这个队列会被独占,其他连接使用不了这个队列

3、autoDelete:是否自动删除,true表示这个队列没有使用的时候会自动删除

4、consumerTag:消费者标签,有消费者独有的一段码,例如:amq.ctag-d8WewQIVswYm7pRnAbvmqQ

5、routingKey:路由键,交换机根据路由对队列的指向,direct、topic需要路由键,fanout、headers不需要路由键

6、AMQP.BasicProperties.Builder:构建器,发送消息basicPublish方法所需的BasicProperties参数

7、alternate-exchange:备用交换机,在exchangeDeclare方法的map参数中设置备用交换机

8、deliveryTag:消息序号,消息的编号,从1开始

9、correlationId:消息标识符可从发送者的AMQP.BasicProperties.Builder设置发出

10、x-match:交换机headers类型时匹配表示,any代表匹配一条则可,all表示需全部匹配,标准按照接收者标准,假如消费者比生产者多一条匹配规则,即使其他的规则匹配上也收不到消息

11、replyCode:错误码,生产者消息退回时携带

12、replyText:退回信息描述,生产者消息退回时携带

 

二、队列发送消息

1、消费者


/**
* 消费者
* @author Administrator
*/
public class FirstConsumer {

public static void main(String[] args) throws Exception {
Connection connection = RabbitMqUtils.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("test1", true, false, false, null);

Consumer consumer = new DefaultConsumer(channel){

@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws UnsupportedEncodingException {
System.out.println("===========================");
System.out.println("routingKey => " + envelope.getRoutingKey());
System.out.println("deliveryTag => " + envelope.getDeliveryTag());
System.out.println("message => " + new String(body, "UTF-8"));
}

};

channel.basicConsume("test1", true, consumer);
}

}

2、生产者

/**
 * 生产者
 * @author Administrator
 */
public class FirstProducer {

    public static void main(String[] args) throws Exception {
        String routingKey = "test1";
        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("test1", true, false, false, null);
        String message = "hello, rabbitmq";
        channel.basicPublish("", routingKey, null, message.getBytes());
        channel.close();
        connection.close();
    }

}

3、消费者回调

/**
 * 消费者回调类
 * @author Administrator
 */
public class CallbackConsumer {

    private static final String EXCHANGE_NAME = "callbackExchange";
    private static final String ALTER_EXCHANGE_NAME = "alterExchange";
    private static final String QUEUE_NAME = "callbackQueue";
    private static final String ROUTING_KEY = "key1";

    public static void main(String[] args) throws Exception {
        // 创建连接
        Connection connection = RabbitMqUtils.getConnection();
        // 创建通道
        Channel channel = connection.createChannel();
        // 创建备用交换机参数
        Map<String, Object> params = new HashMap<>(1);
        params.put(RabbitMqUtils.CONST_ALTER_EXCHANGE, ALTER_EXCHANGE_NAME);
        // 设置交换机和备用交换机
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT, true, false, params);
        channel.exchangeDeclare(ALTER_EXCHANGE_NAME, BuiltinExchangeType.DIRECT, true);

        // 设置队列 exclusive 选择不独占 false
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        // 绑定队列
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);

        channel.basicConsume(QUEUE_NAME,
                // 接收消息回调
                new DeliverCallback() {
                    @Override
                    public void handle(String consumerTag, Delivery message) throws IOException {
                        long deliveryTag = message.getEnvelope().getDeliveryTag();
                        String correlationId = message.getProperties().getCorrelationId();
                        // 输出消费者标识符,消费者通道可能有多个消费者者
                        System.out.println("consumerTag => " + consumerTag);
                        // 输出消息序号
                        System.out.println("deliveryTag => " + deliveryTag);
                        // 输出消息标识符
                        System.out.println("correlationId => " + correlationId);
                        // 输出消息
                        System.out.println("message => " + new String(message.getBody(), "UTF-8"));
                        System.out.println("================================================================");
                        // 手动确认消息接收和处理
                        channel.basicAck(deliveryTag, false);
                    }
                },
                // 取消订阅(删除队列)回调
                new CancelCallback() {
                    @Override
                    public void handle(String consumerTag) throws IOException {
                        System.out.println("consumerTag => " + consumerTag);
                    }
                },
                // 异常断电回调
                new ConsumerShutdownSignalCallback() {
                    @Override
                    public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) {
                        System.out.println("consumerTag => " + consumerTag);
                        System.out.println("message => " + sig.getMessage());
                    }
                }
        );
    }

}

4、生产者回调

/**
 * 生产者回调类
 * @author Administrator
 */
public class CallbackProducer {

    private static final String EXCHANGE_NAME = "callbackExchange";
    private static final String ALTER_EXCHANGE_NAME = "alterExchange";
    private static final String QUEUE_NAME = "callbackQueue";

    public static void main(String[] args) throws Exception {
        // 创建连接
        Connection connection = RabbitMqUtils.getConnection();
        // 创建通道
        Channel channel = connection.createChannel();
        // 设置备用交换机参数
        Map<String, Object> params = new HashMap<>(1);
        params.put("alternate-exchange", ALTER_EXCHANGE_NAME);
        // 设置交换机和备用交换机
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT, true, false, params);
        channel.exchangeDeclare(ALTER_EXCHANGE_NAME, BuiltinExchangeType.DIRECT, true);

        // 设置队列 exclusive 选择不独占 false
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        // 绑定队列
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "key1");
        // 设置确认发送监听
        channel.addConfirmListener(new ConfirmListener() {
            // 发送成功调用
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("ack deliveryTag => " + deliveryTag);
            }
            // 发送失败调用
            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("nack deliveryTag => " + deliveryTag);
            }
        });
        // 添加消息路由失败调用(交换机配置错误、路由键不匹配、队列不存在、队列和交换机绑定错误)交换机绑定队列时会有路由,路由错误导致没发回调用
        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("replyCode => " + replyCode);
                System.out.println("replyText => " + replyText);
                System.out.println("exchange => " + exchange);
                System.out.println("routingKey => " + routingKey);
                System.out.println("properties => " + properties);
                System.out.println("message => " + new String(body, "UTF-8"));
            }
        });
        AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
        builder.deliveryMode(MessageProperties.BASIC.getDeliveryMode());
        builder.priority(MessageProperties.BASIC.getPriority());
        builder.correlationId("123");

        String message = "测试";
        // 已有绑定的路由键发送消息
        channel.basicPublish(EXCHANGE_NAME, "key1", builder.build(), message.getBytes());
        // 没有绑定的路由键发送消息
        channel.basicPublish(EXCHANGE_NAME, "key2", builder.build(), message.getBytes());
        // 等待一会再关闭通道和连接,防止没有接收到回调
        Thread.sleep(10000);
        channel.close();
        connection.close();
    }

}

 

三、交换机exchange

1、direct类型,需要routingKey路由键

a、消费者

/**
 * 根据routingKey来路由到队列
 * @author Administrator
 */
public class DirectConsumer {

    private static final String EXCHANGE_NAME = "exchange_direct";
    private static final String QUEUE_NAME = "queue_direct";


    public static void main(String[] args) throws Exception {
        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "key1");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 消费者标签
                System.out.println("consumerTag => " + consumerTag);
                String routingKey = envelope.getRoutingKey();
                // 路由键
                System.out.println("routingKey => " + routingKey);
                long deliveryTag = envelope.getDeliveryTag();
                // 消息序号
                System.out.println("deliveryTag => " + deliveryTag);
                String contentType = properties.getContentType();
                // 内容类型
                System.out.println("contentType => " + contentType);
                // 消息
                System.out.println("message => " + new String(body, "UTF-8"));
                channel.basicAck(deliveryTag, true);
            }
        };
        channel.basicConsume(QUEUE_NAME, false, consumer);
    }

}

b、生产者

/**
 * @author Administrator
 */
public class DirectProducer {

    private static final String EXCHANGE_NAME = "exchange_direct";
    private static final String QUEUE_NAME = "queue_direct";

    public static void main(String[] args) throws Exception {
        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

        String message1 = "exchange_direct message1";
        String message2 = "exchange_direct message2";
        String message3 = "exchange_direct message3";

        channel.basicPublish(EXCHANGE_NAME, "key1", null, message1.getBytes(StandardCharsets.UTF_8));
        channel.basicPublish(EXCHANGE_NAME, "key2", null, message2.getBytes(StandardCharsets.UTF_8));
        channel.basicPublish(EXCHANGE_NAME, "key3", null, message3.getBytes(StandardCharsets.UTF_8));

        channel.close();
        connection.close();
    }

}

2、fanout类型,不需要routingKey路由键

a、消费者

/**
 * @author Administrator
 */
public class FanoutConsumer {

    private static final String EXCHANGE_NAME = "exchange_fanout";

    public static void main(String[] args) throws Exception {
        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, EXCHANGE_NAME, "");
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 消费者标签
                System.out.println("consumerTag => " + consumerTag);
                String routingKey = envelope.getRoutingKey();
                // 路由键
                System.out.println("routingKey => " + routingKey);
                long deliveryTag = envelope.getDeliveryTag();
                // 消息序号
                System.out.println("deliveryTag => " + deliveryTag);
                String contentType = properties.getContentType();
                // 内容类型
                System.out.println("contentType => " + contentType);
                // 消息
                System.out.println("message => " + new String(body, "UTF-8"));
                channel.basicAck(deliveryTag, true);
            }
        };
        channel.basicConsume(queueName, false, consumer);
    }

}

b、生产者

/**
 * 使用fanout直接发送到交换机上,不需要绑定队列,广播形式发送的消息,所有绑定交换机消费者都可以收到,路由可写也可不写
 * @author Administrator
 */
public class FanoutProducer {

    private static final String EXCHANGE_NAME = "exchange_fanout";

    public static void main(String[] args) throws Exception {
        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
        String message = "fanout类型";
        channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes(StandardCharsets.UTF_8));

        channel.close();
        connection.close();
    }

}

3、headers类型,使用x-match表示,any匹配任一即可,all匹配全部,不需要routingKey路由键

a、消费者1,any匹配,匹配信息数量一致,两条相同一条不同,可收到信息

/**
 * @author Administrator
 */
public class HeadConsumer1 {

    private static final String EXCHANGE_NAME = "exchange_head";
    private static final String QUEUE_NAME = "queue_head1";
    private static final String ROUTING_KEY = "routing_key_head";

    public static void main(String[] args) throws Exception {
        // 构建头部信息,无缺失,两条对应
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-match", "any");
        headers.put("level", "admin");
        headers.put("log", "info");
        headers.put("tag", "ok");

        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.HEADERS, true);
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);

        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY, headers);
        channel.basicConsume(QUEUE_NAME, false, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 消费者标签
                System.out.println("consumerTag => " + consumerTag);
                String routingKey = envelope.getRoutingKey();
                // 路由键
                System.out.println("routingKey => " + routingKey);
                long deliveryTag = envelope.getDeliveryTag();
                // 消息序号
                System.out.println("deliveryTag => " + deliveryTag);
                String contentType = properties.getContentType();
                // 内容类型
                System.out.println("contentType => " + contentType);
                // 消息
                System.out.println("message => " + new String(body, "UTF-8"));
                channel.basicAck(deliveryTag, true);
            }
        });

    }
}

b、消费者2,any匹配,消费者比生产者少一条匹配信息,一条相同一条不同,可收到消息

/**
 * @author Administrator
 */
public class HeadConsumer2 {

    private static final String EXCHANGE_NAME = "exchange_head";
    private static final String QUEUE_NAME = "queue_head2";
    private static final String ROUTING_KEY = "routing_key_head";

    public static void main(String[] args) throws Exception {
        // 构建头部信息,有缺失,一条对应
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-match", "any");
        headers.put("level", "admin");
        headers.put("log", "error");

        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.HEADERS, true);
        String queue = channel.queueDeclare(QUEUE_NAME, true, false, false, null).getQueue();
        System.out.println("queue => " + queue);
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY, headers);

        channel.basicConsume(QUEUE_NAME, false, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 消费者标签
                System.out.println("consumerTag => " + consumerTag);
                String routingKey = envelope.getRoutingKey();
                // 路由键
                System.out.println("routingKey => " + routingKey);
                long deliveryTag = envelope.getDeliveryTag();
                // 消息序号
                System.out.println("deliveryTag => " + deliveryTag);
                String contentType = properties.getContentType();
                // 内容类型
                System.out.println("contentType => " + contentType);
                // 消息
                System.out.println("message => " + new String(body, "UTF-8"));
                channel.basicAck(deliveryTag, true);
            }
        });
    }

}

c、消费者3,all匹配,消费者匹配信息比生产者少一条,两条信息相同,可收到信息

/**
 * @author Administrator
 */
public class HeadConsumer3 {

    private static final String EXCHANGE_NAME = "exchange_head";
    private static final String QUEUE_NAME = "queue_head3";
    private static final String ROUTING_KEY = "routing_key_head";

    public static void main(String[] args) throws Exception {
        // 构建头部信息,有缺失
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-match", "all");
        headers.put("level", "admin");
        headers.put("log", "info");

        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.HEADERS, true);
        String queue = channel.queueDeclare(QUEUE_NAME, true, false, false, null).getQueue();
        System.out.println("queue => " + queue);
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY, headers);

        channel.basicConsume(QUEUE_NAME, false, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 消费者标签
                System.out.println("consumerTag => " + consumerTag);
                String routingKey = envelope.getRoutingKey();
                // 路由键
                System.out.println("routingKey => " + routingKey);
                long deliveryTag = envelope.getDeliveryTag();
                // 消息序号
                System.out.println("deliveryTag => " + deliveryTag);
                String contentType = properties.getContentType();
                // 内容类型
                System.out.println("contentType => " + contentType);
                // 消息
                System.out.println("message => " + new String(body, "UTF-8"));
                channel.basicAck(deliveryTag, true);
            }
        });
    }

}

4、消费者4,all匹配,与消费者1使用同一个队列,全部匹配成功,与消费者1两个只有一个收到消息

/**
 * 绑定同一队列,heaers匹配条件不同,只有一个连接得到数据,没有广播,方式应该是轮询
 * @author Administrator
 */
public class HeadConsumer4 {

    private static final String EXCHANGE_NAME = "exchange_head";
    private static final String QUEUE_NAME = "queue_head1";
    private static final String ROUTING_KEY = "routing_key_head";

    public static void main(String[] args) throws Exception {
        // 构建头部信息,无缺失,全对应
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-match", "all");
        headers.put("level", "admin");
        headers.put("log", "info");
        headers.put("tag", "yes");

        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.HEADERS, true);
        String queue = channel.queueDeclare(QUEUE_NAME, true, false, false, null).getQueue();
        System.out.println("queue => " + queue);
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY, headers);

        channel.basicConsume(QUEUE_NAME, false, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 消费者标签
                System.out.println("consumerTag => " + consumerTag);
                String routingKey = envelope.getRoutingKey();
                // 路由键
                System.out.println("routingKey => " + routingKey);
                long deliveryTag = envelope.getDeliveryTag();
                // 消息序号
                System.out.println("deliveryTag => " + deliveryTag);
                String contentType = properties.getContentType();
                // 内容类型
                System.out.println("contentType => " + contentType);
                // 消息
                System.out.println("message => " + new String(body, "UTF-8"));
                channel.basicAck(deliveryTag, true);
            }
        });
    }

}

5、消费者5,all匹配,消费者匹配信息比生产者多一条,除多出的一条其余的消息形同,未收到消息,可见消息是按照消费者的标准匹配

/**
 * @author Administrator
 */
public class HeadConsumer5 {

    private static final String EXCHANGE_NAME = "exchange_head";
    private static final String QUEUE_NAME = "queue_head5";
    private static final String ROUTING_KEY = "routing_key_head";

    public static void main(String[] args) throws Exception {
        // 构建头部信息,比发送者多一条信息,没有送达,标准应该是按照接受者为标准匹配
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-match", "all");
        headers.put("level", "admin");
        headers.put("log", "info");
        headers.put("tag", "yes");
        headers.put("match", "abandon");

        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.HEADERS, true);
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);

        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY, headers);
        channel.basicConsume(QUEUE_NAME, false, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 消费者标签
                System.out.println("consumerTag => " + consumerTag);
                String routingKey = envelope.getRoutingKey();
                // 路由键
                System.out.println("routingKey => " + routingKey);
                long deliveryTag = envelope.getDeliveryTag();
                // 消息序号
                System.out.println("deliveryTag => " + deliveryTag);
                String contentType = properties.getContentType();
                // 内容类型
                System.out.println("contentType => " + contentType);
                // 消息
                System.out.println("message => " + new String(body, "UTF-8"));
                channel.basicAck(deliveryTag, true);
            }
        });
    }

}

6、消费者6,all匹配,消费者匹配信息与生产者相同,路由不同,可收到消息

/**
 * 测试有头部条件时,如果路由缺失或不同,还可以收到信息
 * @author Administrator
 */
public class HeadConsumer6 {

    private static final String EXCHANGE_NAME = "exchange_head";
    private static final String QUEUE_NAME = "queue_head6";
    private static final String ROUTING_KEY = "";

    public static void main(String[] args) throws Exception {
        // 构建头部信息
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-match", "all");
        headers.put("level", "admin");
        headers.put("log", "info");
        headers.put("tag", "yes");

        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.HEADERS, true);
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);

        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY, headers);
        channel.basicConsume(QUEUE_NAME, false, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 消费者标签
                System.out.println("consumerTag => " + consumerTag);
                String routingKey = envelope.getRoutingKey();
                // 路由键
                System.out.println("routingKey => " + routingKey);
                long deliveryTag = envelope.getDeliveryTag();
                // 消息序号
                System.out.println("deliveryTag => " + deliveryTag);
                String contentType = properties.getContentType();
                // 内容类型
                System.out.println("contentType => " + contentType);
                // 消息
                System.out.println("message => " + new String(body, "UTF-8"));
                channel.basicAck(deliveryTag, true);
            }
        });
    }

}

7、生产者1

/**
 * 测试包含匹配信息缺失
 * @author Administrator
 */
public class HeadProducer {

    private static final String EXCHANGE_NAME = "exchange_head";
    private static final String ROUTING_KEY = "routing_head";

    public static void main(String[] args) throws Exception {
        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.HEADERS, true);
        // 构建匹配信息
        Map<String, Object> headers = new HashMap<>();
        headers.put("level", "admin");
        headers.put("log", "info");
        headers.put("tag", "yes");

        AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
        builder.deliveryMode(MessageProperties.BASIC.getDeliveryMode());
        builder.priority(MessageProperties.BASIC.getPriority());
        builder.headers(headers);

        String message = "发送成功";

        channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, builder.build(), message.getBytes(StandardCharsets.UTF_8));

        channel.close();
        connection.close();

    }

}

8、生产者2

/**
 *
 * @author Administrator
 */
public class HeadProducerTest {

    private static final String EXCHANGE_NAME = "exchange_head";
    private static final String ROUTING_KEY = "";

    public static void main(String[] args) throws Exception {
        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.HEADERS, true);
        // 构建匹配信息
        Map<String, Object> headers = new HashMap<>();
        headers.put("level", "admin");
        headers.put("log", "info");
        headers.put("tag", "yes");

        AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
        builder.deliveryMode(MessageProperties.BASIC.getDeliveryMode());
        builder.priority(MessageProperties.BASIC.getPriority());
        builder.headers(headers);

        String message = "发送成功";

        channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, builder.build(), message.getBytes(StandardCharsets.UTF_8));

        channel.close();
        connection.close();

    }

}

4、topic类型,需要routingKey路由键,生产以广播形式发送到交换机,交换机分发到每一个绑定交换机的队列,如果两个消费者使用同一个队列,消息只会给一个消费者

a、消费者1,使用#占位符,可占位0个和0以上词

/**
 * @author Administrator
 */
public class TopicConsumer1 {

    private static final String EXCHANGE_NAME = "exchange_topic";
    private static final String QUEUE_NAME = "queue_topic1";

    public static void main(String[] args) throws Exception {
        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);

        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        // 测试#是否可占位0个
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "#.key1.topic");
        // 测试#是否可占位多个
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "key2.#.topic");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 消费者标签
                System.out.println("consumerTag => " + consumerTag);
                String routingKey = envelope.getRoutingKey();
                // 路由键
                System.out.println("routingKey => " + routingKey);
                long deliveryTag = envelope.getDeliveryTag();
                // 消息序号
                System.out.println("deliveryTag => " + deliveryTag);
                String contentType = properties.getContentType();
                // 内容类型
                System.out.println("contentType => " + contentType);
                // 消息
                System.out.println("message => " + new String(body, "UTF-8"));
                channel.basicAck(deliveryTag, true);
            }
        };
        channel.basicConsume(QUEUE_NAME, false, consumer);
    }

}

b、消费者2,使用*占位符,只能占位一个词

/**
 * @author Administrator
 */
public class TopicConsumer2 {

    private static final String EXCHANGE_NAME = "exchange_topic";
    private static final String QUEUE_NAME = "queue_topic2";

    public static void main(String[] args) throws Exception {
        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);

        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        // 测试*是否可占位1个
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "key3.*.topic");
        // 测试*是否只占位1个
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "key2.*.topic");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 消费者标签
                System.out.println("consumerTag => " + consumerTag);
                String routingKey = envelope.getRoutingKey();
                // 路由键
                System.out.println("routingKey => " + routingKey);
                long deliveryTag = envelope.getDeliveryTag();
                // 消息序号
                System.out.println("deliveryTag => " + deliveryTag);
                String contentType = properties.getContentType();
                // 内容类型
                System.out.println("contentType => " + contentType);
                // 消息
                System.out.println("message => " + new String(body, "UTF-8"));
                channel.basicAck(deliveryTag, true);
            }
        };
        channel.basicConsume(QUEUE_NAME, false, consumer);
    }

}

3、生产者

/**
 * 可对路由键模糊匹配,单词之间用“,”隔开,“*”占位一个单词,“#”占位0或多个单词
 * @author Administrator
 */
public class TopicProducer {

    private static final String EXCHANGE_NAME = "exchange_topic";

    public static void main(String[] args) throws Exception {
        Connection connection = RabbitMqUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);

        String message1 = "exchange_direct message1";
        String message2 = "exchange_direct message2";
        String message3 = "exchange_direct message3";

        channel.basicPublish(EXCHANGE_NAME, "key1.topic", null, message1.getBytes(StandardCharsets.UTF_8));
        channel.basicPublish(EXCHANGE_NAME, "key2.my.test.topic", null, message2.getBytes(StandardCharsets.UTF_8));
        channel.basicPublish(EXCHANGE_NAME, "key3.like.topic", null, message3.getBytes(StandardCharsets.UTF_8));

        channel.close();
        connection.close();
    }

}

 

posted @ 2025-05-18 23:53  此时不卷何时卷  阅读(28)  评论(0)    收藏  举报