弹簧状态机同时用于多个线程

时间:2016-05-12 10:41:44

标签: java spring state-machine spring-statemachine

我在单独的线程中有20个并发用户处理订单。如何使用弹簧状态机维持状态?

我在尝试:

public class myclass extends EnumStateMachineConfigurerAdapter<OrderState, OrderEvents>

 @Override
    public void configure(StateMachineTransitionConfigurer<OrderState, OrderEvents> transitions)
            throws Exception {
        transitions
                .withExternal()
                .source(OrderState.A).target(OrderState.B)
                .event(OrderEvents.X)
                .and()
                .withExternal()
                .source(OrderState.A).target(OrderState.C)
                .event(OrderEvents.Y)
@Override
    public void configure(StateMachineConfigurationConfigurer<OrderState, OrderEvents> config) throws Exception {
        config
                .withConfiguration()
                .autoStartup(true)
                .listener(new OrderStateMachineListener());
    }

但是它开始了; y告诉我状态机,而不是命令:

@Override
    public void stateChanged(State<OrderState, OrderEvents> from, State<OrderState, OrderEvents> to) {
        System.out.println("Order state changed to " + to.getId());
    }

我还有其他选择,但这个选项对每个事件看起来不太好:

stateMachine.stop();
        stateMachine
                .getStateMachineAccessor()
                .doWithAllRegions(access -> access.resetStateMachine(new DefaultStateMachineContext<>(sourceState, null, null, null)));
        stateMachine.start();
        stateMachine.sendEvent(event);

1 个答案:

答案 0 :(得分:1)

终于工作了。我不得不在配置级别使用@EnableStateMachineFactory而不是@EnableStateMachine,并且从调用程序:

@Autowired
StateMachineFactory<String, String> factory;

    public void getOrderStatus(long id) {
        StateMachine<String, String> stateMachine = factory.getStateMachine();
        stateMachine.start();
        stateMachine.sendEvent();
    }