2017-11-16 16 views
1

実行時にこれを構成する最も簡単な方法は何でしょうか?実行時に@RabbitListenerを構築する最も簡単な方法

@RabbitListener(bindings = @QueueBinding(
    value = @Queue(value = "providedAtRuntime", durable = "true"), 
    exchange = @Exchange(value = "providedAtRuntime", ignoreDeclarationExceptions = "true"), 
    key = "providedAtRuntime"), containerFactory = "cFac") 
public class RabbitProcessor { 
    @RabbitHandler 
    public void receive (String smth){ 
     System.out.println(smth); 
    } 
} 

私はリスナーを定義したいが、実行時に交換、キュー名とバインディングを提供したい。また、このリスナーは自動的には起動しないでください。同時に、バインディングやキューなどを自動的に宣言する必要があります。stop()と呼ばれると、消費を停止する必要があります。

+0

この? https://stackoverflow.com/questions/14268981/modify-a-class-definitions-annotation-string-parameter-at-runtime – Eugene

答えて

4

注釈では不可能だと思いますが、カスタムを作成することもできますSimpleMessageListenerContainer。ここ

はシンプルなソリューションです:

public static AbstractMessageListenerContainer startListening(RabbitAdmin rabbitAdmin, Queue queue, Exchange exchange, String key, MessageListener messageListener) { 
    rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(key).noargs()); 
    SimpleMessageListenerContainer listener = new SimpleMessageListenerContainer(rabbitAdmin.getRabbitTemplate().getConnectionFactory()); 
    listener.addQueues(queue); 
    listener.setMessageListener(messageListener); 
    listener.start(); 

    return listener; 
} 

、あなたはとしてそれを呼び出すことができます。

ConfigurableApplicationContext ctx = SpringApplication.run(DemoApplication.class, args); 

ConnectionFactory connectionFactory = ctx.getBean(ConnectionFactory.class); 
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory); 
AbstractMessageListenerContainer container = startListening(rabbitAdmin, rabbitAdmin.declareQueue(), 
     new DirectExchange("amq.direct"), "testRoute", message -> { 
      System.out.println(new String(message.getBody())); 
     }); 

そして、あなたは

AbstractMessageListenerContainer.destroy()またはAbstractMessageListenerContainer.stop()それをすることができます。

春のブート1.5.8.RELEASEとRabbitMQの3.6.10でテスト

+0

ありがとうございます。私はこのアプローチについて知っていた。私はちょうどrabbitAdminを直接使用せずに、これよりもさらに簡単なものがあるかどうかをチェックしたいと思っていました。 – bojanv55

+1

いいえ、それは単に不可能であるか効率的でないために何もありません。 –

+0

@Artem Bilan - 接続が失われたときにキュー、交換、バインディングが再宣言されることはありますか?リスナーコンテナも自動的に再接続されますか? – bojanv55

関連する問題