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 @ 2024-07-28 17:08  临渊不羡渔  阅读(10)  评论(0编辑  收藏  举报