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



一个类似于向任意虚拟主机发送消息/与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继续使用"/">

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

更新 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!

并且有效负载 3 的消息转到 vHost foo

RabbitAdmin不能做超出其ConnectionFactory允许的事情。因此,vHost 类似于主机/端口,无法从最终用户的角度进行管理。

看:

/**
* 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无法为您创建虚拟主机。这不是 AMQP 协议操作。 有关详细信息,请参阅 https://docs.spring.io/spring-amqp/docs/2.2.7.RELEASE/reference/html/#management-rest-api。

最新更新