spring-statemachine的企业可用级开发指南3多个状态机共存

7次阅读

共计 7142 个字符,预计需要花费 18 分钟才能阅读完成。

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 , 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 的版本,这都是我血与泪的忠告。

码云配套代码地址

正文完
 0