如何使用Spring Boot将消息发布到RabbitMQ(在运行时提供队列详细信息)?

huangapple go评论79阅读模式
英文:

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 @Autowiredyou have to create amqpAdmin in a @Bean like this:

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

Is also explained here

huangapple
  • 本文由 发表于 2020年10月19日 13:01:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64421424.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定