一.、使用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);// 發送消息到 RabbitMQrabbitTemplate.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 {@Beanpublic DirectExchange orderExchange() {return new DirectExchange("order.exchange");}@Beanpublic Queue orderQueue() {return new Queue("order.queue");}@Beanpublic 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 {@Beanpublic Consumer<Long> orderCreated() {return orderId -> System.out.println("【通知服務】訂單 " + orderId + " 創建成功,發送通知!");}
}
(3) 配置 application.yml
spring:cloud:stream:bindings:orderCreated-out-0:destination: order-eventsorderCreated-in-0:destination: order-eventsdefaultBinder: rabbit