Spring 状态机极简使用

Spring 状态机极简使用

本文不探讨状态机的思想与Spring状态机的架构,仅做快速实现参考。
Spring 状态机官方文档
项目参考代码

基于SpringBoot配置的快速集成案例

maven 依赖配置

<dependency>
<groupId>org.springframework.statemachine</groupId>
<artifactId>spring-statemachine-starter</artifactId>
<version>4.0.0</version>
</dependency>

java代码

@Configuration
@EnableStateMachine
public class Config1Enums
extends EnumStateMachineConfigurerAdapter<States, Events> {
@Override
public void configure(StateMachineStateConfigurer<States, Events> states)
throws Exception {
states
.withStates()
.initial(States.S1)
.end(States.SF)
.states(EnumSet.allOf(States.class));
}
}

极简自定义集成案例

该案例支持每次以入参状态作为初始状态获取一个新的状态机。可作为最小接入代价状态机使用。

/**
* 自定义状态机工厂配置
* <br/>
* <code>
* <a href="https://docs.spring.io/spring-statemachine/docs/4.0.0/reference/index.html#devdocs">官方案例参考</a>
* </code>
*/
@Slf4j
@RequiredArgsConstructor
@Component
public class SimpleStateMachineService {
public StateMachine<States, Events> getStateMachine(States initStates) throws Exception {
StateMachineBuilder.Builder<States, Events> builder = StateMachineBuilder.builder();
builder.configureConfiguration()
.withConfiguration().autoStartup(true)
.and()
.withVerifier().enabled(true);
builder.configureStates().withStates()
.initial(initStates)
.states(EnumSet.allOf(States.class));
builder.configureTransitions()
.withExternal()
.event(E1).source(S1).target(S2)
.guard(guard())
.action(action())
.and()
.withExternal()
.event(E2).source(S2).target(S0)
.guard(guard())
.action(action());
return builder.build();
}
private Guard<States, Events> guard() {
return stateModel -> {
Object data = stateModel.getMessageHeader("data");
return Boolean.TRUE.equals(data);
};
}
private Action<States, Events> action() {
return context -> log.info("源状态:{},目标状态:{},事件:{}", context.getSource().getId(), context.getTarget().getId(), context.getEvent());
}
}
``
posted @   临渊不羡渔  阅读(49)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2021-07-28 记录一次docker启动失败
点击右上角即可分享
微信分享提示