Spring Boot集成RabbitMQ-之6大模式总结
在Spring Boot中,整合RabbitMQ可以通过Spring AMQP和Spring Data AMQP来实现。以下是Spring Boot整合RabbitMQ的6大模式的示例代码:
- 简单模式(Simple Message Broker)
@Autowired
private AmqpTemplate amqpTemplate;
public void sendMessage(String message) {
amqpTemplate.convertAndSend("simple.queue", message);
}
- 工作模式(Work Queue)
@RabbitListener(queues = "work.queue")
public void processMessage(String message) {
System.out.println("Received message: " + message);
}
- 发布/订阅模式(Publish/Subscribe)
@Autowired
private AmqpTemplate amqpTemplate;
public void sendMessage(String message) {
amqpTemplate.convertAndSend("exchange.fanout", "", message);
}
- 路由模式(Routing)
@Autowired
private AmqpTemplate amqpTemplate;
public void sendMessage(String message) {
amqpTemplate.convertAndSend("exchange.direct", "routing.key", message);
}
- 主题模式(Topics)
@Autowired
private AmqpTemplate amqpTemplate;
public void sendMessage(String message) {
amqpTemplate.convertAndSend("exchange.topic", "routing.key", message);
}
- RPC模式(Remote Procedure Call)
发送消息的一侧:
@Autowired
private RabbitTemplate rabbitTemplate;
public String rpcCall(String message) {
CorrelationData correlationId = new CorrelationData("123");
rabbitTemplate.convertSendAndReceive("exchange.direct", "routing.key", message, correlationId);
Message response = rabbitTemplate.receiveAndConvert("reply.queue", 10000);
return (String) response.getPayload();
}
接收消息并作出回复的一侧:
@RabbitListener(queues = "rpc.queue")
public String handleRpcCall(String message) {
// handle message
return response;
}
以上代码仅为示例,实际使用时需要配置Exchange、Queue、Binding等信息。在RPC模式中,还需要配置回复队列和回调机制。
评论已关闭