[英]How to send messages to multiple jms (active mq) brokers from the same application?
我在本地有2個具有嵌入式活動mq實例的應用程序(服務器)。
現在,我需要為此服務器創建一個客戶端。
我已經閱讀過答案: https ://stackoverflow.com/a/43401330/2674303
並嘗試重復此操作:
我注冊了2個連接工廠:
@Bean
@Primary
public ConnectionFactory bitFinexExchangeJmsConnectionFactory() {
return new ActiveMQConnectionFactory("tcp://localhost:61616");
}
@Bean
public ConnectionFactory hitbtcExchangeJmsConnectionFactory() {
return new ActiveMQConnectionFactory("tcp://localhost:61617");
}
注冊了2個jms模板:
@Bean
@Primary
public JmsTemplate bitfinexJmsTemplate() {
JmsTemplate jmsTemplate = new JmsTemplate();
jmsTemplate.setConnectionFactory(bitFinexExchangeJmsConnectionFactory());
jmsTemplate.setDefaultDestinationName("robotCommand_bitfinex");
return jmsTemplate;
}
@Bean
public JmsTemplate hitBtcJmsTemplate() {
JmsTemplate jmsTemplate = new JmsTemplate();
jmsTemplate.setConnectionFactory(hitbtcExchangeJmsConnectionFactory());
jmsTemplate.setDefaultDestinationName("robotCommand_hitbtc");
return jmsTemplate;
}
並在我的spring boot應用程序中編寫了以下main方法:
ConfigurableApplicationContext context = SpringApplication.run(RobotApplication.class, args);
JmsTemplate bitfinexJmsTemplate = context.getBean(JmsTemplate.class, "bitfinexJmsTemplate");
bitfinexJmsTemplate.convertAndSend("robotCommand", "message to bitfinex");
JmsTemplate hitBtcJmsTemplate = context.getBean(JmsTemplate.class, "hitBtcJmsTemplate");
hitBtcJmsTemplate.convertAndSend("robotCommand", "message to hitbtcc");
在客戶端中,我看到只有message to bitfinex
。
我開始調查問題,發現hitBtcJmsTemplate
使用bitFinexExchangeJmsConnectionFactory
。 我試圖更改我的主要方法代碼:
ConfigurableApplicationContext context = SpringApplication.run(RobotApplication.class, args);
JmsTemplate bitfinexJmsTemplate = context.getBean(JmsTemplate.class, "bitfinexJmsTemplate");
bitfinexJmsTemplate.convertAndSend("robotCommand", "message to bitfinex");
JmsTemplate hitBtcJmsTemplate = context.getBean(JmsTemplate.class, "hitBtcJmsTemplate");
hitBtcJmsTemplate.setConnectionFactory((ConnectionFactory) context.getBean("hitbtcExchangeJmsConnectionFactory")); // <---- additional line
hitBtcJmsTemplate.convertAndSend("robotCommand", "message to hitbtcc");
並且兩個服務器都收到了消息。
因此很明顯我的配置是錯誤的。 請幫助糾正它。
您使用了錯誤的getBean方法!
<T> T getBean(java.lang.Class<T> requiredType,
java.lang.Object... args)
改成
JmsTemplate bitfinexJmsTemplate = context.getBean("bitfinexJmsTemplate", JmsTemplate.class);
JmsTemplate hitBtcJmsTemplate = context.getBean("hitBtcJmsTemplate", JmsTemplate.class);
您應該指定@Qualifier
。 如果使用@Autowired
獲取bean,則可以這樣做
@Autowired
@Qualifier("hitBtcJmsTemplate")
JmsTemplate hitBtcJmsTemplate;
如果要從ApplicationContext獲取它,則必須使用BeanFactory。 因為Beanfactory具有指定Qualifier的方法。 你可以這樣
BeanFactoryAnnotationUtils.qualifiedBeanOfType(applicationContext.getBeanFactory(), JmsTemplate.class, "hitBtcJmsTemplate");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.