import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.util.HashMap; import java.util.Map; /** * 为队列设置 TTL,过期后队列将自动删除 * @author hxstrive.com 2022/2/24 */ public class TtlDemo3 { /** 交换器名称 */ private final String EXCHANGE_NAME = "exchange-" + TtlDemo3.class.getSimpleName(); /** 队列名称 */ private final String QUEUE_NAME = "queue-" + TtlDemo3.class.getSimpleName(); public static void main(String[] args) throws Exception { TtlDemo3 demo = new TtlDemo3(); demo.sender(); } /** * 生产者 * @throws Exception */ private void sender() throws Exception { // 创建连接 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.1"); factory.setPort(5672); Connection connection = factory.newConnection(); // 创建信道 Channel channel = connection.createChannel(); // 声明交换器 channel.exchangeDeclare(EXCHANGE_NAME, "topic"); // 声明队列 Map<String,Object> argss =new HashMap<String,Object>() ; argss.put("x-expires", 6000); // 设置过期时间为 6 秒 channel.queueDeclare(QUEUE_NAME, true, false, false, argss) ; channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "*.hxstrive.com"); // 关闭连接 channel.close(); connection.close(); } }