RabbitMQ TTL 过期时间 和 死信队列

TTL 过期时间

  • TTL是time to live的缩写。也就是生存时间。
  • RabbitMQ支持队列的过期时间, 从消息入队列开始计算, 只要超过了队列的超时时间配置, 那么消息会自动清除
  • RabbitMQ支持消息的过期时间, 在消息发送时可以进行指定
队列过期时间设置
package com.example.rabbitmq.ttl;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 生产者
 */
public class producer {

    public static void main(String[] args) throws IOException, TimeoutException {

        //1,创建工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        //2, 获取连接
        Connection connection = connectionFactory.newConnection();
        //3, 通过connection创建一个channel
        Channel channel = connection.createChannel();

        String exchangeName = "ttl_exchange";
        String routingKey = "ttl.save";
        String queueName = "ttl_queue";

        //声明一个交换机, 也可以在消费端声明
        channel.exchangeDeclare(exchangeName, "topic", true);
        //声明一个队列
        //队列参数
        Map<String, Object> arg = new HashMap<String, Object>(3);
        // 设置队列中消息过期时间,50秒过期(毫秒为单位)
        arg.put("x-message-ttl", 50 * 1000);
        //声明一个TTL队列
        channel.queueDeclare(queueName, true, false, false, arg);
        //建立关系
        channel.queueBind(queueName, exchangeName, routingKey);

        //5.1 发送消息
        String msg = "hello rabbitmq send retuen message!";
        channel.basicPublish(exchangeName, routingKey, true,null, msg.getBytes());
        channel.close();
        connection.close();
    }
}
消息过期时间设置
package com.example.rabbitmq.ttl;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class producerTTLMessage {

    public static void main(String[] args) throws IOException, TimeoutException {

        //1,创建工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        //2, 获取连接
        Connection connection = connectionFactory.newConnection();
        //3, 通过connection创建一个channel
        Channel channel = connection.createChannel();

        String exchangeName = "ttl_exchange";
        String routingKey = "ttl.save2";
        String queueName = "ttl_queue2";

        //4, 声明交换机, 队列 并建立关系(也可以在消费端声明)
        channel.exchangeDeclare(exchangeName, "topic", true);
        //声明一个队列
        channel.queueDeclare(queueName, true, false, false, new HashMap<>());
        //建立关系
        channel.queueBind(queueName, exchangeName, routingKey);

        //5, 发送消息, 单个消息设置ttl.
        String msg = "hello rabbitmq send retuen message!";
        Map<String,Object> headers = new HashMap<>();
        //设置message参数
        AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                .deliveryMode(2)
                .contentEncoding("UTF-8")
                .expiration("10000")    //消息过期时间
                .headers(headers)       //自定义headers
                .build();
        channel.basicPublish(exchangeName, routingKey, true, properties, msg.getBytes());
        channel.close();
        connection.close();
    }
}

死信队列

DLX, Dead-Letter-Exchange
利用DLX, 当消息一个队列中变成死信(dead message)之后,它能被重新publish到另一个Exchange,这个Exchange就是DLX。

消息变成死信的几种情况:

  1. 消息被拒绝(basic.reject/ basic.nack)并且requeue=false。
  2. 消息TTL过期
  3. 队列达到最大长度
  • DLX是一个正常的Exchange,和一般的Exchange没有区别,它能在任何的队列上被指定,实际上就是设置某个队列的属性。
  • 当这个队列中有死信时,RabbitMQ就会自动的将这个消息重新发布到设置的Exchange上,进而被路由到另一个队列。
  • 可以监听这个队列中消息做相应的处理,这个特性可以弥补RabbitMQ3.0以前支持的immediate参数的功能。

死信队列设置:

  1. 首先需要这是死信队列的Exchange和queue,然后进行绑定:
         Exchange:dlx.exchange
         Queue:dlx.queue
         RoutingKey:#
  2. 然后我们进行正常的交换机,队列,绑定。之后加一个参数 arguments.put(“x-dead-letter-exchange”, “dlx.exchange”);

消费者代码:

package com.example.rabbitmq.ttl.dlx;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 消费者
 */
public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1,创建工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        //2,获取连接
        Connection connection = connectionFactory.newConnection();
        //3,通过connection创建一个channel
        Channel channel = connection.createChannel();

        //4,exchange, routingkey, queue, 并将queue和交换机绑定
        //设置交换机
        String exchangeName = "test_dlx_exchange";
        String routingKey = "dlx.#";
        String queueName = "test_dlx_queue";

        //死信队列配置
        String dlxExchangeName = "dlx.exchange";
        String dlxQueueName = "dlx.queue";

        //声明一个交换机
        channel.exchangeDeclare(exchangeName, "topic", true);

        //声明一个普通队列
        //队列参数
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", dlxExchangeName);
        channel.queueDeclare(queueName, true, false, false, arguments);
        channel.queueBind(queueName, exchangeName, routingKey);

        //声明死信队列
        channel.exchangeDeclare(dlxExchangeName, "topic", true, false, null);
        channel.queueDeclare(dlxQueueName, true, false, false, null);
        channel.queueBind(dlxQueueName, dlxExchangeName, "#");

        //5,创建消费者//
        channel.basicConsume(queueName, true, new MyConsumer(channel));
    }
}
package com.example.rabbitmq.ttl.dlx;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

/**
 * 自定义消费者
 */
public class MyConsumer extends DefaultConsumer {

    public MyConsumer(Channel channel) {
        super(channel);
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties,  byte[] body){
        System.out.println("----- consumer message -----");
        System.out.println("body = " + new String(body));
    }
}

生产者代码:

package com.example.rabbitmq.ttl.dlx;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 生产者
 */
public class producer {

    public static void main(String[] args) throws IOException, TimeoutException {

        //1,创建工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        //2, 获取连接
        Connection connection = connectionFactory.newConnection();
        //3, 通过connection创建一个channel
        Channel channel = connection.createChannel();

        String exchangeName = "test_dlx_exchange";
        String routingKey = "dlx.save";

        //5, 发送消息
        String msg = "hello rabbitmq send retuen message!";
        for (int i = 0; i < 5; i++) {
            AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                    .deliveryMode(2)
                    .contentEncoding("UTF-8")
                    .expiration("10000")
                    .build();
            channel.basicPublish(exchangeName, routingKey, true, properties, msg.getBytes());
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值