英文:
How to publish message to rabbit MQ(queue details provided at runtime) using springboot?
问题
如何将消息发布到 Rabbit MQ,在运行时提供队列详细信息。
有许多关于发布消息的文章,但队列是在应用程序属性文件中提到的。
英文:
How to publish message to rabbit MQ where queue details are provided at runtime.
There are many articles on publishing messages but the queues are being mentioned in application properties file.
答案1
得分: 1
如果您的意思是在运行时设置队列名称,您可以使用 RabbitTemplate
类和 convertAndSend
方法发送消息。参考链接:reference)
假设您的类类似于以下内容:
@Component
public class MessageSender {
@Autowired
private RabbitTemplate rabbitTemplate;
...
}
您可以添加以下方法:
public void sendToQueue(String queueName) {
rabbitTemplate.convertAndSend(queueName, "Hello from Spring!");
}
public void sendToExchange(String exchangeName, String routingKey) {
rabbitTemplate.convertAndSend(exchangeName, routingKey, "Hi exchange!");
}
但是,如果您指的是在运行时创建队列本身,则需要使用 AmqpAdmin 作为 @Autowired
(推荐),或在每次调用中定义它。
@Autowired
private AmqpAdmin amqpAdmin;
在任何方法内部,您可以使用所需的参数(名称、持久性等)创建一个 Queue 对象,如下所示:
Queue queue = new Queue(queueName, ...);
amqpAdmin.declareQueue(queue);
如果您想要使用 @Autowired
,您需要在 @Bean
中创建 amqpAdmin
,如下所示:
@Bean
public AmqpAdmin amqpAdmin() {
return new RabbitAdmin(yourConnectionFactory);
}
也可以在这里找到更详细的说明:here
英文:
If you mean set the queue name at run time you can send messages using RabbitTemplate
class and convertAndSend
method. (reference)
Assuming your class is something like this:
@Component
public class MessageSender {
@Autowired
private RabbitTemplate rabbitTemplate;
...
}
You can add these methods:
public void sendToQueue(String queueName) {
rabbitTemplate.convertAndSend(queueName, "Hello from Spring!");
}
public void sendToExchange(String exchangeName, String routingKey) {
rabbitTemplate.convertAndSend(exchangeName, routingKey, "Hi exchange!");
}
But if you refer to create the Queue itself at runtime then you need an AmqpAdmin as @Autowired
(recommended) or definiting it in every call.
@Autowired
private AmqpAdmin amqpAdmin;
And inside any method you can create a Queue object with desired parammeters (name, durable... anything else)
Something like this:
Queue queue = new Queue(queueName, ...);
amqpAdmin.declareQueue(queue);
If you want to use @Autowired
you have to create amqpAdmin
in a @Bean
like this:
@Bean
public AmqpAdmin amqpAdmin() {
return new RabbitAdmin(yourConnectionFactory);
}
Is also explained here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论