一.、使用RabbitMQ来实现
(1) 生产者(订单微服务)
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private final RabbitTemplate rabbitTemplate;
public OrderService(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
public void createOrder(Long orderId) {
// 创建订单逻辑
System.out.println("订单创建成功: " + orderId);
// 发送消息到 RabbitMQ
rabbitTemplate.convertAndSend("order.exchange", "order.created", orderId);
}
}
(2) 消费者(通知微服务)
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class NotificationService {
@RabbitListener(queues = "order.queue")
public void handleOrderCreated(Long orderId) {
System.out.println("【通知服务】订单 " + orderId + " 创建成功,发送通知!");
}
}
(3) 配置 RabbitMQ 交换机和队列
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
@Bean
public DirectExchange orderExchange() {
return new DirectExchange("order.exchange");
}
@Bean
public Queue orderQueue() {
return new Queue("order.queue");
}
@Bean
public Binding binding(Queue orderQueue, DirectExchange orderExchange) {
return BindingBuilder.bind(orderQueue).to(orderExchange).with("order.created");
}
}
二. 使用 Spring Cloud Stream
Spring Cloud Stream 结合 Kafka 或 RabbitMQ,可以简化微服务间的事件驱动架构。
(1) 生产者
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private final StreamBridge streamBridge;
public OrderService(StreamBridge streamBridge) {
this.streamBridge = streamBridge;
}
public void createOrder(Long orderId) {
System.out.println("订单创建成功: " + orderId);
// 发送事件
streamBridge.send("orderCreated-out-0", orderId);
}
}
(2) 消费者
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import java.util.function.Consumer;
@Service
public class NotificationService {
@Bean
public Consumer<Long> orderCreated() {
return orderId -> System.out.println("【通知服务】订单 " + orderId + " 创建成功,发送通知!");
}
}
(3) 配置 application.yml
spring:
cloud:
stream:
bindings:
orderCreated-out-0:
destination: order-events
orderCreated-in-0:
destination: order-events
defaultBinder: rabbit