jon*_*nua 0 java spring spring-statemachine
我有一个状态机
@EnableStateMachine
@Configuration
public class StateMachineConfiguration extends EnumStateMachineConfigurerAdapter<Status, Event> {
@Override
public void configure(StateMachineStateConfigurer<Status, Event> states) throws Exception {
states.withStates()
.initial(Status.DRAFT)
.states(EnumSet.allOf(Status.class));
}
@Override
public void configure(StateMachineTransitionConfigurer<Status, Event> transitions) throws Exception {
transitions
.withExternal()
.target(Status.INVITATION).source(Status.DRAFT)
.event(Event.INVITED)
.guard(new Guard())
.action(new ActionInvited())
.and()
.withExternal()
.target(Status.DECLINED).source(Status.INVITATION)
.event(Event.DECLINED)
.action(new ActionDeclined());
}
@Override
public void configure(StateMachineConfigurationConfigurer<Status, Event> config) throws Exception {
config.withConfiguration().autoStartup(true);
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个模型,例如Order。模型保留在 DB 中。我从数据库中提取模型,现在我的模型有一个 status Order.status == INVITATION。我想用状态机继续处理模型,但状态机的实例将开始处理初始状态DRAFT但我需要从状态INVITATION继续处理。换句话说,我想执行
stateMachine.sendEvent(MessageBuilder
.withPayload(Event.DECLINED)
.setHeader("orderId", order.id)
.build()
)
Run Code Online (Sandbox Code Playgroud)
并执行操作ActionDeclined()。我不想在数据库中保留状态机的上下文。我想在运行时将 stateMachine 的状态设置为我的模型的状态。我怎样才能以正确的方式做到这一点?使用 DefaultStateContext 构造函数还是有其他更漂亮的方法?
一种可能的方法是动态创建StateMachine并使用Order. 在这种情况下,您需要执行以下步骤:
StateMachine在所有地区重置Order从数据库加载状态DefaultStateMachineContext并相应地填充假设您有一个构建方法,该方法返回用于处理订单事件的新状态机(使用StateMachineFactory),但对于现有订单,它将从数据库中重新水化状态。
StateMachine<Status, Event> build(long orderId) {
orderService.getOrder(orderId) //returns Optional
.map(order -> {
StateMachine<Status, Event> sm = stateMachineFactory.getStateMachine(Long.toString(orderId));
sm.stop();
rehydrateState(sm, sm.getExtendedState(), order.getStatus());
sm.start();
return sm;
})
.orElseGet(() -> createNewStateMachine(orderId);
}
void rehydrateState(StateMachine<Status, Event> newStateMachine, ExtendedState extendedState, Status orderStatus) {
newStateMachine.getStateMachineAccessor().doWithAllRegions(sma ->
sma.resetStateMachine(new DefaultStateMachineContext<>(orderStatus, null, null, extendedState));
});
}
Run Code Online (Sandbox Code Playgroud)