1、多个状态机的搞法
在实际的企业应用中,基本不可能只有一个状态机流程在跑,比如订单,肯定是很多个订单在运行,每个订单都有自己的订单状态机流程,但上一章的例子,大家可以试一下,当执行到一个状态时,再次刷新页面,不会有任何日志出现,当一个状态流程执行到某个状态,再次执行这个状态,是不会有任何输出的,因为状态机的机制是只有在状态切换的时候才会事件(event)触发,所以我们这一章讲多个状态机的并行执行。
首先,靠上一章例子里面的手打定制一个StateMachineConfig的做法,就只能是有一个状态机流程制霸整个项目,这种霸道的做法肯定是不行啦,要想多个状态机流程并行,那么就要请builder出场了,看代码:
private final static String MACHINEID = "orderMachine";
public StateMachine<OrderStates, OrderEvents> build(BeanFactory beanFactory) throws Exception {
StateMachineBuilder.Builder<OrderStates, OrderEvents> builder = StateMachineBuilder.builder();
System.out.println("构建订单状态机");
builder.configureConfiguration()
.withConfiguration()
.machineId(MACHINEID)
.beanFactory(beanFactory);
builder.configureStates()
.withStates()
.initial(OrderStates.UNPAID)
.states(EnumSet.allOf(OrderStates.class));
builder.configureTransitions()
.withExternal()
.source(OrderStates.UNPAID).target(OrderStates.WAITING_FOR_RECEIVE)
.event(OrderEvents.PAY).action(action())
.and()
.withExternal()
.source(OrderStates.WAITING_FOR_RECEIVE).target(OrderStates.DONE)
.event(OrderEvents.RECEIVE);
return builder.build();
}
有没有似曾相识的感觉,里面描述订单状态机的初始状态,状态机的流程代码和StateMachineConfig几乎是一样的,但是都配置在StateMachineBuilder里面
StateMachineBuilder.Builder<OrderStates, OrderEvents> builder = StateMachineBuilder.builder();
这是完整的builder类代码:
import java.util.EnumSet;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.action.Action;
import org.springframework.statemachine.config.StateMachineBuilder;
import org.springframework.stereotype.Component;
@Component
public class OrderStateMachineBuilder {
private final static String MACHINEID = "orderMachine";
/**
* 构建状态机
*
* @param beanFactory
* @return
* @throws Exception
*/
public StateMachine<OrderStates, OrderEvents> build(BeanFactory beanFactory) throws Exception {
StateMachineBuilder.Builder<OrderStates, OrderEvents> builder = StateMachineBuilder.builder();
System.out.println("构建订单状态机");
builder.configureConfiguration()
.withConfiguration()
.machineId(MACHINEID)
.beanFactory(beanFactory);
builder.configureStates()
.withStates()
.initial(OrderStates.UNPAID)
.states(EnumSet.allOf(OrderStates.class));
builder.configureTransitions()
.withExternal()
.source(OrderStates.UNPAID).target(OrderStates.WAITING_FOR_RECEIVE)
.event(OrderEvents.PAY).action(action())
.and()
.withExternal()
.source(OrderStates.WAITING_FOR_RECEIVE).target(OrderStates.DONE)
.event(OrderEvents.RECEIVE);
return builder.build();
}
@Bean
public Action<OrderStates, OrderEvents> action() {
return new Action<OrderStates, OrderEvents>() {
@Override
public void execute(StateContext<OrderStates, OrderEvents> context) {
System.out.println(context);
}
};
}
}
在完整的代码里面我们看到有个东西没讲,那就是MACHINEID,在builder的配置代码里面,有这么一段
builder.configureConfiguration()
.withConfiguration()
.machineId(MACHINEID)
.beanFactory(beanFactory);
machineId是状态机的配置类和事件实现类的关联,和它关联的是OrderEventConfig,代码如下:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.statemachine.annotation.OnTransition;
import org.springframework.statemachine.annotation.WithStateMachine;
@WithStateMachine(id="orderMachine")
public class OrderEventConfig {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 当前状态UNPAID
*/
@OnTransition(target = "UNPAID")
public void create() {
logger.info("---订单创建,待支付---");
}
......
}
这个后面的内容和上一章的OrderSingleEventConfig一模一样,但在类的上面注解了这一句:
@WithStateMachine(id="orderMachine")
这个id对应的就是OrderStateMachineBuilder 里面的MACHINEID,被builder写到.machineId(MACHINEID)里面。这样,OrderStateMachineBuilder对应上一章的StateMachineConfig多个状态机的实现版本,OrderEventConfig对应上一章的OrderSingleEventConfig,基本一样,只是和OrderStateMachineBuilder通过machineid做了关联。现在我们来看怎么用上它。
在controller里面引用这个类:
@Autowired
private OrderStateMachineBuilder orderStateMachineBuilder;
然后使用它
@RequestMapping("/testOrderState")
public void testOrderState(String orderId) throws Exception {
StateMachine<OrderStates, OrderEvents> stateMachine = orderStateMachineBuilder.build(beanFactory);
// 创建流程
stateMachine.start();
// 触发PAY事件
stateMachine.sendEvent(OrderEvents.PAY);
// 触发RECEIVE事件
stateMachine.sendEvent(OrderEvents.RECEIVE);
// 获取最终状态
System.out.println("最终状态:" + stateMachine.getState().getId());
}
这其实就是每次请求testOrderState就会生成一个新的statemachine,所以每次刷新testOrderState请求都会看到日志显示:
构建订单状态机
orderMachine
2019-05-03 19:24:23.734 INFO 11752 --- [nio-9991-exec-1] tConfig$$EnhancerBySpringCGLIB$$29e58541 : ---订单创建,待支付---
2019-05-03 19:24:23.754 INFO 11752 --- [nio-9991-exec-1] o.s.s.support.LifecycleObjectSupport : started org.springframework.statemachine.support.DefaultStateMachineExecutor@133d52dd
2019-05-03 19:24:23.755 INFO 11752 --- [nio-9991-exec-1] o.s.s.support.LifecycleObjectSupport : started UNPAID DONE WAITING_FOR_RECEIVE / UNPAID / uuid=52b44103-22af-49cc-a645-3aab29212a9e / id=orderMachine
DefaultStateContext [stage=TRANSITION, message=GenericMessage [payload=PAY, headers={id=ed826b85-e069-9a5e-34a1-d78454183143, timestamp=1556882663765}], messageHeaders={id=ade4055c-9b59-6498-501e-0e2a8cfe04b4, _sm_id_=52b44103-22af-49cc-a645-3aab29212a9e, timestamp=1556882663767}, extendedState=DefaultExtendedState [variables={}], transition=AbstractTransition [source=ObjectState [getIds()=[UNPAID], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1027927242, toString()=AbstractState [id=UNPAID, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@4b05dcc, deferred=[], entryActions=[], exitActions=[], stateActions=[], regions=[], submachine=null]], target=ObjectState [getIds()=[WAITING_FOR_RECEIVE], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=422378, toString()=AbstractState [id=WAITING_FOR_RECEIVE, pseudoState=null, deferred=[], entryActions=[], exitActions=[], stateActions=[], regions=[], submachine=null]], kind=EXTERNAL, guard=null], stateMachine=UNPAID DONE WAITING_FOR_RECEIVE / UNPAID / uuid=52b44103-22af-49cc-a645-3aab29212a9e / id=orderMachine, source=null, target=null, sources=null, targets=null, exception=null]
传递的参数:null
2019-05-03 19:24:23.775 INFO 11752 --- [nio-9991-exec-1] tConfig$$EnhancerBySpringCGLIB$$29e58541 : ---用户完成支付,待收货---
传递的参数:null
传递的参数:null
2019-05-03 19:24:23.782 INFO 11752 --- [nio-9991-exec-1] tConfig$$EnhancerBySpringCGLIB$$29e58541 : ---用户已收货,订单完成---
最终状态:DONE
这和之前执行testSingleOrderState是不一样的,testSingleOrderState只有第一次会有日志打出,再执行就没有日志出来了,而testOrderState因为每次都build一个新的statemachine,所以每次都会显示日志出来,这样就能保证每个订单都可以为它build一个新的statemachine,就解决了多个状态机并行执行的问题了。
虽然多个状态机的问题解决了,但是对于实际的企业应用而言,还是有问题。这种简单粗暴的,来一个请求就新增一个状态机的搞法很不经济,而且状态机也不是越多越好,而应该是和业务对象一一对应才行,比如订单,就是一个订单一个状态机,而不是每次订单变化就build的一个。这个问题就用到了状态机的持久化,我们下一章就谈谈持久化问题。
2、有个坑
EventConfig类的@WithStateMachine注解有两个参数可用
public @interface WithStateMachine {
/**
* The name of a state machine bean which annotated bean should be associated.
* Defaults to {@code stateMachine}
*
* @return the state machine bean name
*/
String name() default StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE;
/**
* The id of a state machine which annotated bean should be associated.
*
* @return the state machine id
* @see StateMachine#getId()
*/
String id() default "";
}
我们在上面是用id来关联StateMachineBuilder和EventConfig的,用name是无效的,但这个id是spring-statemachine-starter,2.x版本才有,在1.x版本里面,只有name参数,用name参数StateMachineBuilder和EventConfig关联不上,也就是在builder里面状态变化,eventConfig里面并不会同步触发事件,请大家确认使用的是2.x的版本,这都是我血与泪的忠告。
3.新例子
在上一个例子中,我们实现了多个状态机并存执行,不同的订单有各自的状态机运行,但只有一种状态机,这显然不能满足实际业务的要求,比如我就遇到了订单流程和公文审批流程在同一个项目的情况,所以我们这一章讲怎么让多种状态机共存。
我们先把上一章的例子状态机再复习一下,这是个订单状态机,流程图如下:
定义这个状态机我们用到了OrderEvents,OrderStates来表达状态(states)和事件(events),用OrderStateMachineBuilder来描述初始状态和状态变化流程,用OrderEventConfig来描述这个流程和状态变化过程中需要做的业务。现在我们再弄一个新的状态机流程,表单状态机,流程图如下:
为此,我们同样配套了和订单状态机一样的表单四件套,events,states,StateMachineBuilder和eventConfig。
public enum FormStates {
BLANK_FORM, // 空白表单
FULL_FORM, // 填写完表单
CONFIRM_FORM, // 校验表单
SUCCESS_FORM// 成功表单
}
public enum FormEvents {
WRITE, // 填写
CONFIRM, // 校验
SUBMIT // 提交
}
import java.util.EnumSet;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.config.StateMachineBuilder;
import org.springframework.stereotype.Component;
/**
* 订单状态机构建器
*/
@Component
public class FormStateMachineBuilder {
private final static String MACHINEID = "formMachine";
/**
* 构建状态机
*
* @param beanFactory
* @return
* @throws Exception
*/
public StateMachine<FormStates, FormEvents> build(BeanFactory beanFactory) throws Exception {
StateMachineBuilder.Builder<FormStates, FormEvents> builder = StateMachineBuilder.builder();
System.out.println("构建表单状态机");
builder.configureConfiguration()
.withConfiguration()
.machineId(MACHINEID)
.beanFactory(beanFactory);
builder.configureStates()
.withStates()
.initial(FormStates.BLANK_FORM)
.states(EnumSet.allOf(FormStates.class));
builder.configureTransitions()
.withExternal()
.source(FormStates.BLANK_FORM).target(FormStates.FULL_FORM)
.event(FormEvents.WRITE)
.and()
.withExternal()
.source(FormStates.FULL_FORM).target(FormStates.CONFIRM_FORM)
.event(FormEvents.CONFIRM)
.and()
.withExternal()
.source(FormStates.CONFIRM_FORM).target(FormStates.SUCCESS_FORM)
.event(FormEvents.SUBMIT);
return builder.build();
}
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.statemachine.annotation.OnTransition;
import org.springframework.statemachine.annotation.WithStateMachine;
@WithStateMachine(id="formMachine")
public class FormEventConfig {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 当前状态BLANK_FORM
*/
@OnTransition(target = "BLANK_FORM")
public void create() {
logger.info("---空白表单---");
}
/**
* BLANK_FORM->FULL_FORM 执行的动作
*/
@OnTransition(source = "BLANK_FORM", target = "FULL_FORM")
public void write(Message<FormEvents> message) {
logger.info("---填写完表单---");
}
/**
* FULL_FORM->CONFIRM_FORM 执行的动作
*/
@OnTransition(source = "FULL_FORM", target = "CONFIRM_FORM")
public void confirm(Message<FormEvents> message) {
logger.info("---校验表单---");
}
/**
* CONFIRM_FORM->SUCCESS_FORM 执行的动作
*/
@OnTransition(source = "CONFIRM_FORM", target = "SUCCESS_FORM")
public void submit(Message<FormEvents> message) {
logger.info("---表单提交成功---");
}
}
从代码可以看到深深的套路感,里面除了对流程状态的描述不同外,另外一个不同点就是MACHINEID,在不同的状态机流程中,用MACHINEID来标识不同就能使用多种状态机了,对比一下就很清楚。在builder里面通过MACHINEID来区分
private final static String MACHINEID = "orderMachine";
public StateMachine<OrderStates, OrderEvents> build(BeanFactory beanFactory) throws Exception {
StateMachineBuilder.Builder<OrderStates, OrderEvents> builder = StateMachineBuilder.builder();
System.out.println("构建订单状态机");
builder.configureConfiguration()
.withConfiguration()
.machineId(MACHINEID)
.beanFactory(beanFactory);
...
private final static String MACHINEID = "formMachine";
public StateMachine<FormStates, FormEvents> build(BeanFactory beanFactory) throws Exception {
StateMachineBuilder.Builder<FormStates, FormEvents> builder = StateMachineBuilder.builder();
System.out.println("构建表单状态机");
builder.configureConfiguration()
.withConfiguration()
.machineId(MACHINEID)
.beanFactory(beanFactory);
...
对应的在eventconfig里面
@WithStateMachine(id="orderMachine")
public class OrderEventConfig {
...
@WithStateMachine(id="formMachine")
public class FormEventConfig {
通过@WithStateMachine注解的id参数就区分出来了不同的状态机,这个id就是builder里面定义的MACHINEID。然后就是怎么引用的问题了,我们来看controller
@Autowired
private OrderStateMachineBuilder orderStateMachineBuilder;
@Autowired
private FormStateMachineBuilder formStateMachineBuilder;
这样,不同的builder就能同时引用,两种状态机就互不干扰的各自运行了,这是运行的代码:
@RequestMapping("/testOrderState")
public void testOrderState(String orderId) throws Exception {
StateMachine<OrderStates, OrderEvents> stateMachine = orderStateMachineBuilder.build(beanFactory);
System.out.println(stateMachine.getId());
// 创建流程
stateMachine.start();
// 触发PAY事件
stateMachine.sendEvent(OrderEvents.PAY);
// 触发RECEIVE事件
stateMachine.sendEvent(OrderEvents.RECEIVE);
// 获取最终状态
System.out.println("最终状态:" + stateMachine.getState().getId());
}
@RequestMapping("/testFormState")
public void testFormState() throws Exception {
StateMachine<FormStates, FormEvents> stateMachine = formStateMachineBuilder.build(beanFactory);
System.out.println(stateMachine.getId());
// 创建流程
stateMachine.start();
stateMachine.sendEvent(FormEvents.WRITE);
stateMachine.sendEvent(FormEvents.CONFIRM);
stateMachine.sendEvent(FormEvents.SUBMIT);
// 获取最终状态
System.out.println("最终状态:" + stateMachine.getState().getId());
}
分别执行
http://localhost:9991/statemachine/testOrderState 使用StateMachineBuilder创建的多个状态机演示
http://localhost:9991/statemachine/testFormState 多种状态机的演示(上面都是order的状态机,这个是form的状态机)
在日志里面就能看到各自状态机的运行结果了。
目前为止,多个状态机和多种状态机都可以在spring statemachine里面实现了,下一章我们来解决下状态机和实际业务间的数据传输问题,毕竟我们不是为了让状态机自个独自玩耍,和业务数据互通有无才是企业开发的正道。