我正在尝试从一个 uml 模型创建几个状态机实例。我使用 stateMachineFactory。我希望这些机器独立且异步地工作。
如果我只使用“基本”状态,一切都会很好。机器实例可以独立去stateB和StateC。但是,当我使用区域和子状态(stateD)时,机器实例一个接一个地执行 Action (insideStateD1)。请看 .
我发现状态通过 stateMachineTaskExecutor(默认为 SyncTaskExecutor)执行,但子状态通过 taskScheduler(默认为 ConcurrentTaskScheduler)执行。
这是配置:
@Configuration
@EnableStateMachineFactory
public class StateMachineConfig extends StateMachineConfigurerAdapter<String, String> {
@Autowired
StateMachineComponentResolver<String, String> stateMachineComponentResolver;
@Bean
public StateMachineModelFactory<String, String> modelFactory() {
UmlStateMachineModelFactory umlStateMachineModelFactory = new UmlStateMachineModelFactory("classpath:uml/testSM1.uml");
umlStateMachineModelFactory.setStateMachineComponentResolver(stateMachineComponentResolver);
return umlStateMachineModelFactory;
}
@Override
public void configure(StateMachineModelConfigurer<String, String> model) throws Exception {
model
.withModel()
.factory(modelFactory());
}
@Override
public void configure(StateMachineConfigurationConfigurer<String, String> config) throws Exception {
config
.withConfiguration()
// .taskExecutor() // I tried various taskExecutors
// .taskScheduler() // I tried various taskSchedulers
;
}
}
从同一模型实现多个状态机实例的正确方法是什么?
最佳答案
一个SM的多个实例可以通过StateMachineFactory获得.
stateMachineFactory.getStateMachine(); //builds a new state machine
您在 StateMachineConfig 中创建的配置适用于所有 SM 实例。
Spring 状态机使用 TaskExecutor
对于区域执行(与顶级或嵌套区域无关)并且默认情况下它是同步的。要实现异步执行,您需要覆盖默认任务执行器。这可以在配置中实现:
@Override
public void configure(StateMachineConfigurationConfigurer<States, Events> config) throws Exception {
config
.withConfiguration()
//other configs
.taskExecutor(myAsyncTaskExecutor())
}
public TaskExecutor myAsyncTaskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
return taskExecutor;
}
或者通过声明一个bean:
@Bean(name = StateMachineSystemConstants.TASK_EXECUTOR_BEAN_NAME)
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
return taskExecutor;
}
TaskScheduler
用于 Action 执行(与状态或转换相关的 Action )而不用于子状态。
关于java - spring状态机并行实例中子状态的异步执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55328601/