我最近开始学习 Spring 和 spring-amqp,所以这个问题可能显得非常基本,所以请原谅。
我有多个队列,它们位于不同的主机上,并且具有不同的QueueName、RoutingKey、vhost、用户、密码。我正在为这些队列编写发布逻辑,但无法决定是否应该为每个队列分配一个配置类,或者是否可以在 XML 中完成。
创建一个类来获取有关队列的所有信息(主机、虚拟主机、用户名等)的方法工作正常,如 this example 中所述。 。 我创建了一个 @Configuration 类并定义了该队列的所有 bean。但接下来我需要做
ApplicationContext context = new AnnotationConfigApplicationContext(MyQueueConfiguration.class);
AmqpTemplate amqpTemplate = context.getBean(AmqpTemplate.class);
amqpTemplate.convertAndSend("Hello World!!");
所以我的要求是:
- 由于我有许多队列需要在应用程序启动时实例化,因此一旦 tomcat 启动,就应该建立到队列/rabbit 集群的连接/ channel 。
- 一旦有 POST 请求到达我的应用程序,我就需要根据 POST 参数将消息发布到其中一个队列。
所以对于每个队列我总是需要做:
ApplicationContext context = new AnnotationConfigApplicationContext(HelloWorldConfiguration.class);
或者有没有办法让 Spring 加载我所有的队列配置类并只使用该对象,例如:
// calling code when I get a POST request
MyQueueConfigurationClass.publishMessage(payload, queueName);
// The implementation code
public boolean publishMessage(String payload, String queueName){
// Get Bean for the **queueName** somehow
AmqpTemplate amqpTemplate = context.getBean(AmqpTemplate.class);
// Use the bean to send the message
amqpTemplate.convertAndSend(payload);
}
- 那么,如何在不每次都执行
new AnnotationConfigApplicationContext()
的情况下获取确切队列的 amqpTemplate? - 每次请求到达我的服务时都执行 new AnnotationConfigApplicationContext 有什么危害? [我猜测为每个请求创建一个新对象不是一个好主意]
最佳答案
你不应该每次都创建一个新的上下文;这是非常浪费的。
您可以将多个连接工厂(每个 Rabbit 主机一个)添加到根(或 Web)上下文,然后使用 Routing Connection Factory与 sendConnectionFactorySelectorExpression
一起根据您发送的消息选择正确的主机。
或者,您可以简单地为每个服务器连接不同的 RabbitTemplate
。
编辑:
要使用SimpleRoutingConnectionFactory
,请执行以下操作...
try {
SimpleResourceHolder.bind(routingCF, keyForThisMessage);
rabbitTemplate.convertAndSend(message);
}
finally {
SimpleResourceHolder.unbind(routingCF);
}
(这适用于未修改的 RabbitTemplate
)或...
<rabbit:template id="routingTemplate"
connection-factory="rcf"
send-connection-factory-selector-expression="messageProperties.headers['cfKey']" />
<bean id="rcf" class="org.springframework.amqp.rabbit.connection.SimpleRoutingConnectionFactory">
<property name="targetConnectionFactories">
<map>
<entry key="foo" value-ref="cf1"/>
<entry key="bar" value-ref="cf2"/>
</map>
</property>
<property name="defaultTargetConnectionFactory" ref="defaultCF"/>
</bean>
...然后...
this.routingTemplate.convertAndSend("exchange", "routingKey", "xyz", new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) throws AmqpException {
message.getMessageProperties().setHeader("cfKey", "foo");
return message;
}
});
有一个完整的测试用例here .
关于java - spring-amqp 具有不同routingKey的多个队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29133902/