如何让传奇故事开始



我正在尝试使用Axon和Saga设计模式,使用Java在Micorservices之间发送数据我有两个服务,一个用于订单,另一个用于产品CQRS设计模式工作得很好。我的意思是,我将数据发送到axon,然后在我的面板中看到它,然后通过查询获取数据并保存在读取数据库(MySQL(中。今天,我尝试使用Saga设计模式,当创建新订单时,将ReserveProductCommand发送到axon并通过产品服务获取,但Saga没有事件开始,我不知道为什么

下面的订单服务中的Saga类应该得到OrderCreatedEvent并记录消息,但它没有

@Saga
public class OrderSaga {
private final transient CommandGateway commandGateway;
private static final Logger LOGGER = LoggerFactory.getLogger(OrderSaga.class);
@Autowired
public OrderSaga(CommandGateway commandGateway) {
this.commandGateway = commandGateway;
}
@StartSaga
@SagaEventHandler(associationProperty = "orderId")
public void handle(OrderCreatedEvent orderCreatedEvent) {
ReserveProductCommand reserveProductCommand = ReserveProductCommand
.builder()
.orderId(orderCreatedEvent.getOrderId())
.productId(orderCreatedEvent.getProductId())
.quantity(orderCreatedEvent.getQuantity())
.userId(orderCreatedEvent.getUserId())
.build();
LOGGER.info("OrderCreatedEvent handled for orderId: " + reserveProductCommand.getOrderId() + " and productId: " + reserveProductCommand.getProductId());
commandGateway.send(reserveProductCommand, new CommandCallback<ReserveProductCommand, Object>() {
@Override
public void onResult(CommandMessage<? extends ReserveProductCommand> commandMessage, CommandResultMessage<?> commandResultMessage) {
if (commandResultMessage.isExceptional()){
}
}
});
}
@SagaEventHandler(associationProperty = "orderId")
public void handle(ProductReservedEvent productReservedEvent){
LOGGER.info("ProductReservedEvent is called for productId: " + productReservedEvent.getProductId() + " and orderId: " + productReservedEvent.getOrderId());
}
}

低于订单创建事件

@Data
@AllArgsConstructor
@NoArgsConstructor
public class OrderCreatedEvent {
public String orderId;
private String userId;
private String productId;
private int quantity;
private String addressId;
private OrderStatus orderStatus;
}

我已经看到axon仪表板OrderCreatedEvent已经在那里发布了

我认为问题是Axon在Saga上需要一个无arg构造函数。您应该对资源使用字段注入。参考指南中的这段话解释道:

SpringResourceInjector使用Spring的依赖注入机制将资源注入Saga。这意味着您可以根据需要使用setter注入或直接字段注入。需要对要注入的方法或字段进行注释,以便Spring将其识别为依赖项,例如使用@Autowired。

这段话可以在这里找到:https://docs.axoniq.io/reference-guide/axon-framework/sagas/implementation.将构造函数注入更改为字段注入,就像下面的示例一样,应该对您有效:

@Saga
public class OrderSaga {
@Autowired
private final transient CommandGateway commandGateway;
private static final Logger LOGGER = LoggerFactory.getLogger(OrderSaga.class);
// Abbreviated for clarity
}

最新更新