上一节我们介绍了如何构建一个状态机对象,接下来我们开始介绍外部业务代码如何调用状态机
定义事件管理接口
/**
* Author: lehu
* Description: 状态机事件管理类,封装外部业务代码的调用
* Date: Create in 上午11:34 20/5/22
*/
public interface IStateMachineEventManager<E> {
/**
* 触发发送状态变更事件
* @param statusModelDO 状态机模型对象
* @throws Exception
*/
<R> R sendStatusChangeEvent(StatusModelDO statusModelDO, E eventEnum);
}
- 该接口主要封装了外部业务代码对状态机的调用,只需要传入当前需要触发的事件,以及对应逻辑处理的参数对象即可。
定义抽象类
/**
* Author: lehu
* Description:
* Date: Create in 上午11:58 20/5/22
*/
@Slf4j
public abstract class AbstractStateMachineEventManager<S, E> implements IStateMachineEventManager<E> {
@Autowired
private StateMachineBuildFactory<S, E> stateMachineBuildFactory;
//用于状态机上下文持久化
public abstract void stateMachinePersist(StateMachine<S, E> stateMachine, PersisterDO persisterDO) throws Exception;
//用于状态机上下文初始化
public abstract StateMachine<S, E> stateMachineRestore(StateMachine<S, E> stateMachine, PersisterDO persisterDO) throws Exception;
@Override
@SuppressWarnings("unchecked")
public <R> R sendStatusChangeEvent(StatusModelDO statusModelDO, E eventEnum) {
//初始化当前状态机
StateMachine<S, E> stateMachine = initializeMachine(statusModelDO);
//执行状态机事件
Boolean result = statusChangeExecute(stateMachine, statusModelDO, eventEnum);
if (!result) {
throw new RuntimeException("状态机状态执行失败");
}
//执行过程异常处理
RuntimeException exception = (RuntimeException)stateMachine.getExtendedState().getVariables().get(RuntimeException.class);
if (exception != null) {
//业务异常
if (exception instanceof BizException) {
throw exception;
//其他异常
} else {
log.error("状态机内部异常:{}",exception.getMessage(),exception);
if( eventEnum instanceof TakeChangeEventEnum ){
throw new BizException(BasicCode.UNDEFINED_ERROR, ((TakeChangeEventEnum)eventEnum).getDesc() +"处理异常");
}
throw new BizException(BasicCode.UNDEFINED_ERROR, "状态机内部异常,请检查接口程序");
}
}
try {
//持久化状态机
PersisterDO persisterDO = new PersisterDO();
persisterDO.setBizId(statusModelDO.getBizId());
stateMachinePersist(stateMachine, persisterDO);
} catch (Exception e) {
log.error("状态机持久化失败:{}",e.getMessage(),e);
throw new RuntimeException("状态机持久化失败");
}
return (R)stateMachine.getExtendedState().getVariables().get(StateMachineConstants.RETURN_PARAM);
}
/**
* 获取状态机对象
* @param statusModelDO 状态模型对象
* @return 状态机
*/
private StateMachine<S, E> initialize initializeMachine(StatusModelDO statusModelDO) {
log.info("StatusModelDO:" + JSON.toJSONString(statusModelDO));
//构造状态机模板
StateMachine<S, E> stateMachine;
try {
//构造初始化状态机
StateMachine<S, E> srcStateMachine = stateMachineBuildFactory.createStateMachine(getStateMachineType());
//构造当前执行状态
PersisterDO persisterDO = new PersisterDO();
persisterDO.setBizId(statusModelDO.getBizId());
persisterDO.setCurrentState(statusModelDO.getCurrentState());
//恢复当前状态机的上下文内容
stateMachine = stateMachineRestore(srcStateMachine, persisterDO);
} catch (Exception e) {
throw new RuntimeException("初始化状态机失败");
}
if (stateMachine == null) {
throw new RuntimeException("没有找到可用的状态机");
}
log.info("stateMachine:" + JSON.toJSONString(stateMachine));
return stateMachine;
}
private boolean statusChangeExecute(StateMachine<S, E> stateMachine, StatusModelDO statusModelDO, E eventEnum) {
log.info("事件请求statusChangeExecute:" + eventEnum);
//构建消息对象
Message<E> eventMsg = MessageBuilder.withPayload(eventEnum)
.setHeader(StateMachineConstants.STATE_MODEL_DTO, statusModelDO).build();
if (!acceptEvent(stateMachine, eventMsg)) {
throw new RuntimeException("找不到对应状态机事件触发定义");
}
return stateMachine.sendEvent(eventMsg);
}
/**
* 事件执行条件判断
*/
private static <S, E> boolean acceptEvent(StateMachine<S, E> stateMachine, Message<E> eventMsg) {
//获取当前状态
State<S, E> currentState = stateMachine.getState();
for (Transition<S, E> transition : stateMachine.getTransitions()) {
State<S, E> source = transition.getSource();
Trigger<S, E> trigger = transition.getTrigger();
if (currentState != null && trigger != null &&
StateMachineUtils.containsAtleastOne(source.getIds(), currentState.getIds()) &&
trigger.evaluate(new DefaultTriggerContext<>(eventMsg.getPayload()))) {
return true;
}
}
return false;
}
/**
* 获取状态机类型
* @return 状态机类型
*/
public abstract String getStateMachineType();
}
- 该抽象类主要实现了,如何初始化一个状态机对象,并根据当前的事件触发状态机对应的节点动作,最后对执行后的状态机对象做持久化处理。
定义具体类型的事件管理实现类
/**
* Author: lehu
* Description:
* Date: Create in 下午4:16 20/5/22
*/
@Component
public class OrderStateMachineEventManager extends AbstractStateMachineEventManager<OrderStatusEnum, OrderChangeEventEnum> {
@Resource(name = "orderStateMachinePersister")
private StateMachinePersister<OrderStatusEnum, OrderChangeEventEnum, PersisterDO> stateMachinePersister;
@Override
public void stateMachinePersist(StateMachine<OrderStatusEnum, OrderChangeEventEnum> stateMachine,
PersisterDO persisterDO) throws Exception {
stateMachinePersister.persist(stateMachine, persisterDO);
}
@Override
public StateMachine<OrderStatusEnum, OrderChangeEventEnum> stateMachineRestore(
StateMachine<OrderStatusEnum, OrderChangeEventEnum> stateMachine,
PersisterDO persisterDO) throws Exception {
persisterDO.setMachineId(IStateMachineBuilder.ORDER_BUILDER_NAME);
return stateMachinePersister.restore(stateMachine, persisterDO);
}
@Override
public String getStateMachineType() {
return IStateMachineBuilder.ORDER_BUILDER_NAME;
}
}
- 本节介绍了外部调用状态机的实现方式,下一节介绍改管理类中对于状态机上下文持久化的实现。
上一篇:Spring-StateMachine企业级项目应用(三)-状态机构造
下一篇:Spring-StateMachine企业级项目应用(五)-状态机上下文持久化