gpt4 book ai didi

java - spring状态机用于并发多线程

转载 作者:行者123 更新时间:2023-11-30 07:23:17 25 4
gpt4 key购买 nike

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

我正在尝试:

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());
}

但它 on;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);

最佳答案

终于成功了。我必须在配置级别使用 @EnableStateMachineFactory 而不是 @EnableStateMachine,并从调用程序中使用:

@Autowired
StateMachineFactory<String, String> factory;

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

关于java - spring状态机用于并发多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37184547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com