gpt4 book ai didi

java - 多线程环境下的Spring状态机

转载 作者:行者123 更新时间:2023-12-02 03:38:59 24 4
gpt4 key购买 nike

我们刚刚开始使用 Spring 状态机。有几个问题:

  • 每个状态机的状态上下文只有一次吗?
  • 传递给状态机的事件是否以阻塞方式运行?有什么方法可以让它们并行运行,比如每次触发事件时提供一个新的状态机?

这是我的代码:

配置状态和转换:

@Override
public void configure(
StateMachineTransitionConfigurer<WorkFlowStates, WorkFlowEvent> transitions)
throws Exception {
transitions
.withExternal()
.source(WorkFlowStates.ready)
.target(WorkFlowStates.l1Creation)
.event(WorkFlowEvent.createWorkItem)
.action(workFlowCreator.createL1())

在状态转换期间提供操作:

public Action<WorkFlowStates, WorkFlowEvent> createL3() {
return new Action<WorkFlowStates, WorkFlowEvent>() {

public void execute(StateContext<WorkFlowStates, WorkFlowEvent> context) {
System.out.println("l3 creation in action");
Map<Object, Object> variables = context.getExtendedState().getVariables();
Integer counter = (Integer)variables.get("counter");
if(counter == null) counter = 1;
else counter = counter+1;
variables.put("counter", counter);
System.out.println("Counter is "+counter);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
variables.put(Level.l3, WorkItemFactory.createFailureL1L2L3WorkItem());
variables.put("level", Level.l3);
System.out.println("l3 created");
}
};
}

任务执行者:

public void configure(StateMachineConfigurationConfigurer<WorkFlowStates, 
WorkFlowEvent>config)
throws Exception {
config
.withConfiguration()
.autoStartup(true)
.taskExecutor(taskExecutor())
.listener(new WorkFlowStateMachineListener());
}

@Bean(name = StateMachineSystemConstants.TASK_EXECUTOR_BEAN_NAME)
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.afterPropertiesSet();
taskExecutor.setCorePoolSize(5);
return taskExecutor;
}

传递到状态机的事件:

StateMachine<WorkFlowStates, WorkFlowEvent> stateMachine = 
context.getBean(StateMachine.class);

stateMachine.sendEvent(WorkFlowEvent.createWorkItem);
stateMachine.sendEvent(WorkFlowEvent.createWorkItem);

最佳答案

是的,默认行为是阻塞,因为底层 TaskExecutorSyncTaskExecutor。这可以通过 common config 进行更改正如文档中提到的。另请参阅tasks recipe其中默认使用 ThreadPoolTask​​Executor 来并行执行区域。

当远离阻塞机器时,您需要注意机器如何工作以及何时准备好处理进一步的事件,因为机器可能会处于事件被丢弃的状态。通常,您可能需要开始添加延迟事件,以便机器将来在更合适的时间处理这些事件。

关于java - 多线程环境下的Spring状态机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37067736/

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