简体   繁体   English

如何在 Spring Boot 中创建一个 rabbitmq 队列但不使用 @Bean

[英]How to create a rabbitmq Queue in Spring Boot but without using @Bean

In My Scenario I need to create a lots of queues dynamically at run time that is why I don't want to use @Bean instead want to write a function that create queue and I will call it whenever necessary.在我的场景中,我需要在运行时动态创建大量队列,这就是为什么我不想使用 @Bean 而是想编写一个创建队列的函数,我会在必要时调用它。 Here When i use @bean annotation it creates queue on rabbitmq server.在这里,当我使用 @bean 注释时,它会在 rabbitmq 服务器上创建队列。

@Bean
public Queue productQueue(final String queueName) {
    return new Queue(queueName);
} 

But with the same code without @Bean但是使用相同的代码没有@Bean

public Queue productQueue(final String queueName) {
    return new Queue(queueName);
}

when call this function doesn't create queue on rabbitmq server调用此函数时不会在 rabbitmq 服务器上创建队列

Queue queue = <Object>.productQueue("product-queue");

The Queue object must be a bean in the context and managed by Spring. Queue对象必须是上下文中的 bean,并由 Spring 管理。 To create queues dynamically at runtime, define the bean with scope prototype :要在运行时动态创建队列,请使用范围prototype定义 bean:

@Bean
@Scope("prototype")
public Queue productQueue(final String queueName) {
    return new Queue(queueName);
} 

and create queues at runtime using ObjectProvider :并在运行时使用ObjectProvider创建队列:

@Autowired
private ObjectProvider<Queue> queueProvider;

Queue queue1 = queueProvider.getObject("queueName1");
Queue queue2 = queueProvider.getObject("queueName2");

To create rabbitmq queue Dynamically I used following approach and this is best approach if you also want to create exchanges and bind to queue.为了动态创建rabbitmq队列,我使用了以下方法,如果您还想创建交换并绑定到队列,这是最好的方法。

@Autowired
private ConnectionFactory connectionFactory;

@Bean
public AmqpAdmin amqpAdmin() {
 return new RabbitAdmin(connectionFactory);
}

Now you can define a class that creates queue, exchange and bind them现在您可以定义一个创建队列、交换和绑定它们的类

public class rabbitHelper {
  @Autowired
  private RabbitAdmin rabbitAdmin;
  
  public Queue createQueue(String queueName) {
    Queue q  = new Queue(queueName);
    rabbitAdmin.declareQueue(q);
    return q;
  }
 
 public Exchange createExchange(String exchangeName) {
    Exchange exchange  = new DirectExchange(exchangeName);
    rabbitAdmin.declareExchange(exchange);
    return exchange;
  }

public void createBinding(String queueName, String exchangeName, String routingKey) {
    Binding binding = new Binding(queueName, Binding.DestinationType.QUEUE, queueName, routingKey, null);
        rabbitAdmin().declareBinding(binding);
  
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM