天天看点

RabbitMQ知识点整理9-exchangeBind方法详解

我们不仅可以将交换器与队列绑定,也可以将交换器与交换器绑定,后者和前者 ​​RabbitMQ知识点整理8-queueBind方法详解​​ 的用法如出一辙,相应的方法如下:

1.Exchange.BindOk exchangeBind(String destination, String source, String routingKey) throws IOException;
2.Exchange.BindOk exchangeBind(String destination, String source, String routingKey, Map<String, Object> arguments) throws IOException;
3.void exchangeBindNoWait(String destination, String source, String routingKey, Map<String, Object> arguments) throws      

方法中的参数可以参考 ​​RabbitMQ知识点整理6-exchangeDeclare方法详解​​ , 绑定之后,消息从source 交换器转发到 destination 交换器, 某种程度上来说destination 交换器可以看作一个队列

package demo.java.web.amqp.rabbitmq.demo2;

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

import org.junit.Test;

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

/**
 * 交换器与交换器绑定
 * 
 * @author jiangkd
 * @date 2020/10/12
 */
public class ExchangeBindDemo {

    final private String IP_ADDRESS = "127.0.0.1";
    final private int PORT = 5672;
    final private String USERNAME = "root";
    final private String PASSWORD = "root123";
    final private String VIRTUALHOST = "/jiangkd";

    @Test
    public void exchangeBind() throws IOException, TimeoutException {
        //
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(IP_ADDRESS);
        factory.setPort(PORT);
        factory.setVirtualHost(VIRTUALHOST);
        factory.setUsername(USERNAME);
        factory.setPassword(PASSWORD);

        // 创建连接
        Connection connection = factory.newConnection();

        // 创建信道
        Channel channel = connection.createChannel();

        // 定义交换器source和destination, 类型分别是direct和fanout
        channel.exchangeDeclare("source", "direct", true, false, null);
        channel.exchangeDeclare("destination", "fanout", true, false, null);
        // 绑定交换器, 绑定键是 exKey
        channel.exchangeBind("destination", "source", "exKey");
        // 定义队列
        channel.queueDeclare("queue", true, false, false, null);
        // 绑定交换器和队列, 这个交换器类型是fanout, 不用指定路由键, 消息会发送到与此交换器绑定的所有队列
        channel.queueBind("queue", "destination", "");

        // 发布消息
        channel.basicPublish("source", "exKey", null, "Hello World!".getBytes());
    }
}      

生产者发送消息至交换器source 中,交换器source 根据路由键找到与其匹配的另一个交换器destination , 井把消息转发到destination 中, 进而存储在.destination 绑定的队列queue 中,参考图3-1

RabbitMQ知识点整理9-exchangeBind方法详解