首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将spring-rabbit队列地址配置为在运行时可更改

将spring-rabbit队列地址配置为在运行时可更改
EN

Stack Overflow用户
提问于 2016-05-18 01:55:30
回答 1查看 549关注 0票数 2

这是一个监听RabbitMQ队列的web应用程序。一切正常,但是队列的主机地址(127.0.0.1)硬编码在spring xml配置中是不可接受的。

如何从外部注册表动态配置主机?

在应用程序生命周期中,主机地址可能会发生变化。我更希望spring在每次需要队列地址时都会询问一些自定义的编写方法。

代码语言:javascript
复制
<rabbit:queue id="myQueue" />
<rabbit:topic-exchange id="myExchange" name="my-exchange">
    <rabbit:bindings>
        <rabbit:binding queue="myQueue" pattern="my.#.*">
        </rabbit:binding>
    </rabbit:bindings>
</rabbit:topic-exchange>
<rabbit:connection-factory id="connectionFactory" host="127.0.0.1" username="test" password="test" />
<bean id="queListener" class="my.QueListener" />
<rabbit:listener-container id="myListenerContainer" connection-factory="connectionFactory">
    <rabbit:listener ref="queListener" queues="myQueue" />
</rabbit:listener-container>

Spring 4.1,spring-jms,spring-rabbit:1.5,jboss 6.4 eap

EN

回答 1

Stack Overflow用户

发布于 2016-05-31 19:10:20

这是我的解决方案。它可能有一些问题,但基本上是有效的。

代码语言:javascript
复制
private SimpleMessageListenerContainer container;
private static CachingConnectionFactory connectionFactory;

// 1. stop existing consumer

if (container != null) {
    container.stop();
}
if (connectionFactory != null) {
   connectionFactory.destroy();
}

// 2. re-create consumer from scratch
//    imagine all string constants comes from a config

CachingConnectionFactory cf = new CachingConnectionFactory("localhost");
connectionFactory = cf;
cf.setUsername("tst");
cf.setPassword("tst");

RabbitAdmin admin = new RabbitAdmin(cf);
Queue queue = new Queue("myQueue");
admin.declareQueue(queue);
TopicExchange exchange = new TopicExchange("myExchange");
admin.declareExchange(exchange);
admin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(routingKey));

SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cf);
Object listener = new Object() {
    public void handleMessage(byte[] message) { ... }
};
MessageListenerAdapter adapter = new MessageListenerAdapter(listener);
container.setMessageListener(adapter);
container.setQueueNames(queueName);
container.start();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37283208

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档