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;@Componentpublic 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请求都会看到日志显示:

构建订单状态机orderMachine2019-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@133d52dd2019-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=orderMachineDefaultStateContext [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]传递的参数:null2019-05-03 19:24:23.775  INFO 11752 --- [nio-9991-exec-1] tConfig$$EnhancerBySpringCGLIB$$29e58541 : ---用户完成支付,待收货---传递的参数:null传递的参数:null2019-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的版本,这都是我血与泪的忠告。

码云配套代码地址