spring statemachine的企業可用級開發指南3-多個狀態機共存

一、多個狀態機的搞法

    在實際的企業應用中,基本不可能只有一個狀態機流程在跑,好比訂單,確定是不少個訂單在運行,每一個訂單都有本身的訂單狀態機流程,但上一章的例子,你們能夠試一下,當執行到一個狀態時,再次刷新頁面,不會有任何日誌出現,當一個狀態流程執行到某個狀態,再次執行這個狀態,是不會有任何輸出的,由於狀態機的機制是隻有在狀態切換的時候纔會事件(event)觸發,因此咱們這一章講多個狀態機的並行執行。java

    首先,靠上一章例子裏面的手打定製一個StateMachineConfig的作法,就只能是有一個狀態機流程制霸整個項目,這種霸道的作法確定是不行啦,要想多個狀態機流程並行,那麼就要請builder出場了,看代碼:git

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裏面spring

StateMachineBuilder.Builder<OrderStates, OrderEvents> builder = StateMachineBuilder.builder();

這是完整的builder類代碼:app

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的配置代碼裏面,有這麼一段ide

builder.configureConfiguration()
		 		.withConfiguration()
		 		.machineId(MACHINEID)
		 		.beanFactory(beanFactory);

machineId是狀態機的配置類和事件實現類的關聯,和它關聯的是OrderEventConfig,代碼以下:ui

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如出一轍,但在類的上面註解了這一句:spa

@WithStateMachine(id="orderMachine")

這個id對應的就是OrderStateMachineBuilder 裏面的MACHINEID,被builder寫到.machineId(MACHINEID)裏面。這樣,OrderStateMachineBuilder對應上一章的StateMachineConfig多個狀態機的實現版本,OrderEventConfig對應上一章的OrderSingleEventConfig,基本同樣,只是和OrderStateMachineBuilder經過machineid作了關聯。3d

 如今咱們來看怎麼用上它。在controller裏面引用這個類:日誌

@Autowired
	private OrderStateMachineBuilder orderStateMachineBuilder;

而後使用它code

@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的一個。這個問題就用到了狀態機的持久化,咱們下一章就談談持久化問題。

二、有個坑

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的版本,這都是我血與淚的忠告。

碼雲配套代碼地址

相關文章
相關標籤/搜索