RabbitMQ与其他服务协同的实用指南
一、集成总览
二、典型协同场景
三、与主流技术栈的集成方式
四、可靠协同的关键配置
五、快速上手示例
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
@Configuration
public class RabbitConfig {
public static final String QUEUE = "order.created.queue";
public static final String EXCHANGE = "order.events.exchange";
public static final String ROUTING = "order.created";
@Bean public Queue queue() { return new Queue(QUEUE, true); }
@Bean public TopicExchange exchange() { return new TopicExchange(EXCHANGE); }
@Bean public Binding binding(Queue q, TopicExchange e) {
return BindingBuilder.bind(q).to(e).with(ROUTING);
}
}
@Component
public class OrderEventPublisher {
@Autowired private RabbitTemplate rt;
public void publish(String orderId) {
rt.convertAndSend(RabbitConfig.EXCHANGE, RabbitConfig.ROUTING, orderId);
}
}
@Component
public class InventoryHandler {
@RabbitListener(queues = RabbitConfig.QUEUE)
public void handle(String orderId, Channel ch, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
try {
// 1) 扣减库存 2) 写库 3) 其他业务
// 全部成功再确认
ch.basicAck(tag, false);
} catch (Exception e) {
// 可重试或直接入DLQ
ch.basicNack(tag, false, false);
}
}
}