【问题标题】:Set Current State of Spring StateMachine设置 Spring StateMachine 的当前状态
【发布时间】:2020-02-18 17:38:59
【问题描述】:

我开始使用 Spring Statemachine,但在管理对象状态时遇到了一些问题。

我的状态机是 StateMachine 类型。

我的业务对象 Shipment 有一个 ShipmentState 类型的枚举属性(状态),它应该保存剧集的状态机状态。这是我想要的工作流程:

  • 从数据库中加载货件。
  • 从 ShipmentState 设置 Statemachine 的当前状态 在那个 Shipment 实例中。
  • 向状态机发送事件。
  • 从状态机(事件后)获取结果状态并设置 我的 Shipment 实例中的 ShipmentState。
  • 保存 Shipment 实例。

问题是:如何设置现有 StateMachine 的当前状态?

我目前的方法是这样的:对于每个事件,创建一个新的 StateMachine 实例(使用 StateMachineBuilder),根据 Shipment 实例指定初始状态。例如:

@Service
public class StateMachineServiceImpl implements IStateMachineService {

    @Autowired
    private IShipmentService shipmentService;

    @Override
    public StateMachine<ShipmentState, ShipmentEvent> getShipmentStateMachine(Shipment aShipment) throws Exception {

        Builder<ShipmentState, ShipmentEvent> builder = StateMachineBuilder.builder();

        builder.configureStates().withStates()
            .state(ShipmentState.S1)
            .state(ShipmentState.S2)
            .state(ShipmentState.S3)
            .initial(shipmentService.getState())
            .end(ShipmentState.S4);

        builder.configureTransitions().withExternal().source(ShipmentState.S1).target(ShipmentState.S1)
                .event(ShipmentEvent.S3).action(shipmentService.updateAction()).and().withExternal()
                .source(ShipmentState.S1).target(ShipmentState.S2).event(ShipmentEvent.S3)
                .action(shipmentService.finalizeAction()).and().withExternal().source(ShipmentState.S3)
                .target(ShipmentEvent.S4).action(shipmentService.closeAction()).event(ShipmentEvent.S5);

        return builder.build();
    }

}

你觉得我的方法怎么样?

【问题讨论】:

  • Docs 不推荐:构建状态机实例是一项相对繁重的操作。因此,如果您需要(例如)使用状态机处理数据库中的任意状态更改,您需要找到一种更好更快的方法来完成。

标签: spring-statemachine


【解决方案1】:

这种方法没有问题。您可以使用以下代码将状态机重置为特定状态。

stateMachine.getStateMachineAccessor().doWithAllRegions(access -> access
          .resetStateMachine(new DefaultStateMachineContext<>(state, null, null,null)));

您可以根据您的用例将参数传递给DefaultStateMachineContext

【讨论】:

  • Docs 不推荐:构建状态机实例是一项比较繁重的操作。因此,如果您需要(例如)使用状态机处理数据库中的任意状态更改,您需要找到一种更好更快的方法来完成。
猜你喜欢
  • 2015-08-16
  • 2019-03-31
  • 1970-01-01
  • 2016-02-11
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2016-12-07
相关资源
最近更新 更多