Spring AmqpAdmin 在 vHost 中创建交换和队列

Spring AmqpAdmin create exchange & queues in vHost

Send message to arbitrary vhost / exchange with RabbitMQ / Spring AMQP 类似的问题,但我试图让 AmqpAdmin 在特定 vHost

下创建交换

我试过做类似

的事情
SimpleResourceHolder.bind(((RabbitAdmin) amqpAdmin).getRabbitTemplate().getConnectionFactory(), vhost);
...
amqpAdmin.declareExchange(exchange);
...
amqpAdmin.declareQueue(queue);
amqpAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(routingKey));

SimpleResourceHolder.unbind(((RabbitAdmin) amqpAdmin).getRabbitTemplate().getConnectionFactory());

但是 AmqpAdmin 继续使用“/”

有没有办法告诉它在运行时以编程方式使用特定的 vHost?

更新 1: 基于@artem-bilan,我已经(部分)成功了:


    public void sendToTopic(String domain, String topic, String routingKey, Object payload) {
        bindToVirtualHost(template, domain);
        try {
            template.setUsePublisherConnection(true);
            template.convertAndSend(topic, routingKey, payload);
        } finally {
            unbindFromVirtualHost(template);
            template.setUsePublisherConnection(false);
        }
    }

    private void bindToVirtualHost(RabbitTemplate rabbitTemplate, String vHost) {
        AbstractConnectionFactory factory = (AbstractConnectionFactory) rabbitTemplate.getConnectionFactory();
        LOG.debug("binding {} to {}", factory, vHost);
        factory.setVirtualHost(vHost);
    }

    private void unbindFromVirtualHost(RabbitTemplate rabbitTemplate) {
        AbstractConnectionFactory factory = (AbstractConnectionFactory) rabbitTemplate.getConnectionFactory();
        LOG.debug("unbinding {} back to default {}", factory, DEFAULT_VHOST);
        factory.setVirtualHost(DEFAULT_VHOST);
    }

我说(部分)因为如果我这样做:

// pre :Manually create vHost foo

        sendToTopic("bar","myTopic","key","The payload"); // connection error; protocol method: #method<connection.close>(reply-code=530, reply-text=NOT_ALLOWED - vhost TNo not found, as expected
        sendToTopic("foo","myTopic","key","The payload2"); // success, as expected
        sendToTopic("bar","myTopic","key","The payload3"); // success, NOT EXPECTED!

payload3 的消息发送到 vHost foo

RabbitAdmin 不能做超过 ConnectionFactory 允许的事情。因此,vHost 类似于 host/port,无法从最终用户的角度进行管理。

参见:

/**
 * Create a new CachingConnectionFactory given a host name
 * and port.
 * @param hostNameArg the host name to connect to
 * @param port the port number
 */
public CachingConnectionFactory(@Nullable String hostNameArg, int port) {

及其:

public void setVirtualHost(String virtualHost) {

轮到RabbitAdmin就是这样:

/**
 * Construct an instance using the provided {@link ConnectionFactory}.
 * @param connectionFactory the connection factory - must not be null.
 */
public RabbitAdmin(ConnectionFactory connectionFactory) {

所以,要处理不同的vHost,你需要有自己的ConnectionFactoryRabbitAdmin

不,AmqpAdmin 无法为您创建 vHost。这不是 AMQP 协议操作。 有关详细信息,请参阅 https://docs.spring.io/spring-amqp/docs/2.2.7.RELEASE/reference/html/#management-rest-api