java exchangedeclare_RabbitMq之备份交换机(alternate-exchange)

备份交换器,AlternateExchange(AE);

备份交换器是为了实现没有路由到队列的消息,声明交换机的时候添加属性alternate-exchange,声明一个备用交换机,一般声明为fanout类型,这样交换机收到路由不到队列的消息就会发送到备用交换机绑定的队列中。

package com.sky.study.alternate;

import java.io.IOException;

import java.nio.charset.StandardCharsets;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.HashMap;

import java.util.Map;

import com.rabbitmq.client.Channel;

import com.rabbitmq.client.Connection;

import com.rabbitmq.client.MessageProperties;

import com.sky.study.ConnectionUtil;

public class RabbitProducer {

private static final String EXCHANGE_NAME = "exchange_demo";

private static final String BINDING_KEY = "bingkey_demo";

private static final String QUEUE_NAME = "queue_demo";

public static void main(String[] args) throws Exception {

try {

// 创建一个连接

Connection connection = ConnectionUtil.getConnection();

// 创建信道

Channel channel = connection.createChannel();

Map arguments = new HashMap<>(16);

arguments.put("alternate-exchange", "backup-exchange");

channel.exchangeDeclare(EXCHANGE_NAME, "direct", true, false, arguments);

channel.queueDeclare(QUEUE_NAME, true, false, false, null);

channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, BINDING_KEY);

// 声明一个 fanout 类型的交换器,建议此处使用 fanout 类型的交换器

channel.exchangeDeclare("backup-exchange", "fanout", true, false, null);

// 消息没有被路由的之后存入的队列

channel.queueDeclare("unRoutingQueue", true, false, false, null);

channel.queueBind("unRoutingQueue", "backup-exchange", "");

// 发送一条持久化消息

String message = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 没有被正确的路由到消息队列,此时此消息会进入 unRoutingQueue";

try {

// 使用 routingKey

channel.basicPublish(EXCHANGE_NAME, "not-exists-routing-key", true, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes(StandardCharsets.UTF_8));

System.err.println("消息发送完成......");

} catch (IOException e) {

e.printStackTrace();

}

}catch (Exception e) {

e.printStackTrace();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值