Spring StateMachine框架
快速入門
依照之前的風格,我們通過一個簡單的示例來對Spring StateMachine有一個初步的認識。假設我們需要實現一個訂單的相關流程,其中包括訂單創建、訂單支付、訂單收貨三個動作。
下面我們來詳細的介紹整個實現過程:
-
創建一個Spring Boot的基礎工程,並在pom.xml中加入spring-statemachine-core的依賴,具體如下:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.7.RELEASE</version> <relativePath/> </parent>
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.statemachine</groupId> <artifactId>spring-statemachine-core</artifactId> <version>1.2.0.RELEASE</version> </dependency> </dependencies>
|
-
根據上面所述的訂單需求場景定義狀態和事件枚舉,具體如下:
public enum States { UNPAID, |
其中共有三個狀態(待支付、待收貨、結束)以及兩個引起狀態遷移的事件(支付、收貨),其中支付事件PAY會觸發狀態從待支付UNPAID狀態到待收貨WAITING_FOR_RECEIVE狀態的遷移,而收貨事件RECEIVE會觸發狀態從待收貨WAITING_FOR_RECEIVE狀態到結束DONE狀態的遷移。
-
創建狀態機配置類:
@Configuration @EnableStateMachine public class StateMachineConfig extends EnumStateMachineConfigurerAdapter<States, Events> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Override public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception { states .withStates() .initial(States.UNPAID) .states(EnumSet.allOf(States.class)); }
@Override public void configure(StateMachineTransitionConfigurer<States, Events> transitions) throws Exception { transitions .withExternal() .source(States.UNPAID).target(States.WAITING_FOR_RECEIVE) .event(Events.PAY) .and() .withExternal() .source(States.WAITING_FOR_RECEIVE).target(States.DONE) .event(Events.RECEIVE); }
@Override public void configure(StateMachineConfigurationConfigurer<States, Events> config) throws Exception { config .withConfiguration() .listener(listener()); }
@Bean public StateMachineListener<States, Events> listener() { return new StateMachineListenerAdapter<States, Events>() {
@Override public void transition(Transition<States, Events> transition) { if(transition.getTarget().getId() == States.UNPAID) { logger.info("訂單創建,待支付"); return; }
if(transition.getSource().getId() == States.UNPAID && transition.getTarget().getId() == States.WAITING_FOR_RECEIVE) { logger.info("用戶完成支付,待收貨"); return; }
if(transition.getSource().getId() == States.WAITING_FOR_RECEIVE && transition.getTarget().getId() == States.DONE) { logger.info("用戶已收貨,訂單完成"); return; } }
}; }
}
|
在該類中定義了較多配置內容,下面對這些內容一一說明:
-
@EnableStateMachine注解用來啟用Spring StateMachine狀態機功能
-
configure(StateMachineStateConfigurer<States, Events> states)方法用來初始化當前狀態機擁有哪些狀態,其中initial(States.UNPAID)定義了初始狀態為UNPAID,states(EnumSet.allOf(States.class))則指定了使用上一步中定義的所有狀態作為該狀態機的狀態定義。
@Override public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception { |
-
configure(StateMachineTransitionConfigurer<States, Events> transitions)方法用來初始化當前狀態機有哪些狀態遷移動作,其中命名中我們很容易理解每一個遷移動作,都有來源狀態source,目標狀態target以及觸發事件event。
@Override public void configure(StateMachineTransitionConfigurer<States, Events> transitions) throws Exception { transitions .withExternal() .source(States.UNPAID).target(States.WAITING_FOR_RECEIVE) |
-
configure(StateMachineConfigurationConfigurer<States, Events> config)方法為當前的狀態機指定了狀態監聽器,其中listener()則是調用了下一個內容創建的監聽器實例,用來處理各個各個發生的狀態遷移事件。
@Override public void configure(StateMachineConfigurationConfigurer<States, Events> config) throws Exception { config .withConfiguration() .listener(listener()); |
-
StateMachineListener<States, Events> listener()方法用來創建StateMachineListener狀態監聽器的實例,在該實例中會定義具體的狀態遷移處理邏輯,上面的實現中只是做了一些輸出,實際業務場景會會有更負責的邏輯,所以通常情況下,我們可以將該實例的定義放到獨立的類定義中,並用注入的方式加載進來。
-
創建應用主類來完成整個流程:
@SpringBootApplication public class Application implements CommandLineRunner {
public static void main(String[] args) { SpringApplication.run(Application.class, args); }
@Autowired private StateMachine<States, Events> stateMachine;
@Override public void run(String... args) throws Exception { stateMachine.start(); stateMachine.sendEvent(Events.PAY); stateMachine.sendEvent(Events.RECEIVE); }
}
|
在run函數中,我們定義了整個流程的處理過程,其中start()就是創建這個訂單流程,根據之前的定義,該訂單會處於待支付狀態,然后通過調用sendEvent(Events.PAY)執行支付操作,最后通過掉用sendEvent(Events.RECEIVE)來完成收貨操作。在運行了上述程序之后,我們可以在控制台中獲得類似下面的輸出內容:
INFO 2312 --- [ main] eConfig$$EnhancerBySpringCGLIB$$a05acb3d : 訂單創建,待支付 INFO 2312 --- [ main] o.s.s.support.LifecycleObjectSupport : started org.springframework.statemachine.support.DefaultStateMachineExecutor@1d2290ce INFO 2312 --- [ main] o.s.s.support.LifecycleObjectSupport : started DONE UNPAID WAITING_FOR_RECEIVE / UNPAID / uuid=c65ec0aa-59f9-4ffb-a1eb-88ec902369b2 / id=null INFO 2312 --- [ main] eConfig$$EnhancerBySpringCGLIB$$a05acb3d : 用戶完成支付,待收貨 INFO 2312 --- [ main] eConfig$$EnhancerBySpringCGLIB$$a05acb3d : 用戶已收貨,訂單完成
|
其中包括了狀態監聽器中對各個狀態遷移做出的處理。
通過上面的例子,我們可以對如何使用Spring StateMachine做如下小結:
- 定義狀態和事件枚舉
- 為狀態機定義使用的所有狀態以及初始狀態
- 為狀態機定義狀態的遷移動作
- 為狀態機指定監聽處理器
狀態監聽器
通過上面的入門示例以及最后的小結,我們可以看到使用Spring StateMachine來實現狀態機的時候,代碼邏輯變得非常簡單並且具有層次化。整個狀態的調度邏輯主要依靠配置方式的定義,而所有的業務邏輯操作都被定義在了狀態監聽器中,其實狀態監聽器可以實現的功能遠不止上面我們所述的內容,它還有更多的事件捕獲,我們可以通過查看StateMachineListener接口來了解它所有的事件定義:
public interface StateMachineListener<S,E> {
void stateChanged(State<S,E> from, State<S,E> to);
void stateEntered(State<S,E> state);
void stateExited(State<S,E> state);
void eventNotAccepted(Message<E> event);
void transition(Transition<S, E> transition);
void transitionStarted(Transition<S, E> transition);
void transitionEnded(Transition<S, E> transition);
void stateMachineStarted(StateMachine<S, E> stateMachine);
void stateMachineStopped(StateMachine<S, E> stateMachine);
void stateMachineError(StateMachine<S, E> stateMachine, Exception exception);
void extendedStateChanged(Object key, Object value);
void stateContext(StateContext<S, E> stateContext);
}
|
注解監聽器
對於狀態監聽器,Spring StateMachine還提供了優雅的注解配置實現方式,所有StateMachineListener接口中定義的事件都能通過注解的方式來進行配置實現。比如,我們可以將之前實現的狀態監聽器用注解配置來做進一步的簡化:
@WithStateMachine public class EventConfig {
private Logger logger = LoggerFactory.getLogger(getClass());
@OnTransition(target = "UNPAID") public void create() { logger.info("訂單創建,待支付"); }
@OnTransition(source = "UNPAID", target = "WAITING_FOR_RECEIVE") public void pay() { logger.info("用戶完成支付,待收貨"); }
@OnTransition(source = "WAITING_FOR_RECEIVE", target = "DONE") public void receive() { logger.info("用戶已收貨,訂單完成"); }
}
|
上述代碼實現了與快速入門中定義的listener()方法創建的監聽器相同的功能,但是由於通過注解的方式配置,省去了原來事件監聽器中各種if的判斷,使得代碼顯得更為簡潔,擁有了更好的可讀性。