类似的问题 用RabbitMQ Spring AMQP发送消息给任意vhost交换。 但我想拥有 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类似于主机端口,不能从终端用户的角度进行管理。
见。
/**
* 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) {
The RabbitAdmin
,轮到自己,就是这样的。
/**
* Construct an instance using the provided {@link ConnectionFactory}.
* @param connectionFactory the connection factory - must not be null.
*/
public RabbitAdmin(ConnectionFactory connectionFactory) {
所以,为了应对不同的vHost,你需要有自己的vHost ConnectionFactory
和 RabbitAdmin
.
不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不,不。AmqpAdmin
不能为您创建一个vHost。这不是一个AMQP协议操作。https:/docs.spring.iospring-amqpdocs2.2.7.RELEASEreferencehtml#management-rest-api。 更多信息。