【问题标题】:Spring StateMachine reusable statemachine instanceSpring StateMachine 可重用状态机实例
【发布时间】:2023-03-18 21:50:01
【问题描述】:

我有如下图所示的弹簧状态机:

我希望在应用启动时启动状态机。之后它应该进入重新状态,在某个时间(计划)它进入状态 GetOrders 与子状态(GetA、GetB 和 GetC)。之后,如果有一些错误,它应该进入错误,否则如果一切正常,它应该进入 Re-State,它应该等待调度程序。

这是我的配置

@Override
    public void configure(StateMachineConfigurationConfigurer<States, Events> config) throws Exception {
        config.withConfiguration()
          .autoStartup(true)
          .machineId("orderMachine");
    }

这是调度器的方法:

@Scheduled(cron = "0 0 1 1 * *")
    public void startStateMachine() {
        
        StateMachine<States, Events> sm = factory.getStateMachine();
        sm.start();
        sm.sendEvent(Events.ReState);
    }

一切正常,但我注意到每次执行此方法时,正在启动的 stateMachine 与前一个的 UUID 不同,但 Id 相同。所以我想我正在制作状态机的多个实例。是否可以重用相同的状态机或不完成该过程。因为在我的情况下,大多数时候机器的状态应该处于重新状态。可以认为是等待状态。

【问题讨论】:

    标签: java spring state-machine spring-statemachine


    【解决方案1】:

    尝试使用SpringStateMachineService 获取状态机实例,而不是从StateMachineFactory 显式检索它。可以使用Spring提供的default实现:

    @Bean
    public StateMachineService<State, Event> stateMachineService(
            final StateMachineFactory<State, Event> stateMachineFactory) {
        return new DefaultStateMachineService<>(stateMachineFactory);
    }
    

    因此,您的代码将如下所示:

    @Scheduled(cron = "0 0 1 1 * *")
    public void startStateMachine() {
        // here we need to get stateMachineId from some storage
        stateMachineService.acquireStateMachine(stateMachineId, true)
                .sendEvent(Events.ReState);
    }
    

    在上面的代码中,您需要提供特定的状态机 ID。通常,我将它们存储在数据库中,查询它们并为每个实例实例化状态机。 持久化状态机上下文超出了问题的范围。见Persisting State Machine

    【讨论】:

      【解决方案2】:

      那么您的状态机应该很可能是公共的和静态的。这样您就可以确保您的机器只有一个实例。

      【讨论】:

      • 我已将 StateMachine 的创建更改为静态和公共的,但 UUID 仍然不同 :)
      • 我认为您应该提供更多代码来实际使用并进行测试。
      • 提供更多代码是什么意思?状态和事件枚举、转换配置、状态配置、操作?我认为任何这些都无济于事......它只是一个基本配置
      猜你喜欢
      • 1970-01-01
      • 2016-12-07
      • 2019-03-31
      • 1970-01-01
      • 2016-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多