javascript
使用Spring StateMachine框架实现状态机
Spring StateMachine框架可能對于大部分使用Spring的開發者來說還比較生僻,該框架目前差不多也才剛滿一歲多。它的主要功能是幫助開發者簡化狀態機的開發過程,讓狀態機結構更加層次化。前幾天剛剛發布了它的第三個Release版本1.2.0,其中增加了對Spring Boot的自動化配置,既然一直在寫Spring Boot的教程,所以干脆就將該內容也納入進來吧,希望對有需求的小伙伴有一定的幫助。
快速入門
依照之前的風格,我們通過一個簡單的示例來對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, // 待支付
WAITING_FOR_RECEIVE, // 待收貨
DONE // 結束
}
public enum Events {
PAY, // 支付
RECEIVE // 收貨
}其中共有三個狀態(待支付、待收貨、結束)以及兩個引起狀態遷移的事件(支付、收貨),其中支付事件PAY會觸發狀態從待支付UNPAID狀態到待收貨WAITING_FOR_RECEIVE狀態的遷移,而收貨事件RECEIVE會觸發狀態從待收貨WAITING_FOR_RECEIVE狀態到結束DONE狀態的遷移。
創建狀態機配置類:
public class StateMachineConfig extends EnumStateMachineConfigurerAdapter<States, Events> {
private Logger logger = LoggerFactory.getLogger(getClass());
public void configure(StateMachineStateConfigurer<States, Events> states)
throws Exception {
states
.withStates()
.initial(States.UNPAID)
.states(EnumSet.allOf(States.class));
}
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);
}
public void configure(StateMachineConfigurationConfigurer<States, Events> config)
throws Exception {
config
.withConfiguration()
.listener(listener());
}
public StateMachineListener<States, Events> listener() {
return new StateMachineListenerAdapter<States, Events>() {
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))則指定了使用上一步中定義的所有狀態作為該狀態機的狀態定義。
public void configure(StateMachineStateConfigurer<States, Events> states)
throws Exception {
// 定義狀態機中的狀態
states
.withStates()
.initial(States.UNPAID) // 初始狀態
.states(EnumSet.allOf(States.class));
}configure(StateMachineTransitionConfigurer<States, Events> transitions)方法用來初始化當前狀態機有哪些狀態遷移動作,其中命名中我們很容易理解每一個遷移動作,都有來源狀態source,目標狀態target以及觸發事件event。
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);
}configure(StateMachineConfigurationConfigurer<States, Events> config)方法為當前的狀態機指定了狀態監聽器,其中listener()則是調用了下一個內容創建的監聽器實例,用來處理各個各個發生的狀態遷移事件。
public void configure(StateMachineConfigurationConfigurer<States, Events> config)
throws Exception {
config
.withConfiguration()
.listener(listener()); // 指定狀態機的處理監聽器
}StateMachineListener<States, Events> listener()方法用來創建StateMachineListener狀態監聽器的實例,在該實例中會定義具體的狀態遷移處理邏輯,上面的實現中只是做了一些輸出,實際業務場景會會有更負責的邏輯,所以通常情況下,我們可以將該實例的定義放到獨立的類定義中,并用注入的方式加載進來。
創建應用主類來完成整個流程:
public class Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
private StateMachine<States, Events> stateMachine;
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接口中定義的事件都能通過注解的方式來進行配置實現。比如,我們可以將之前實現的狀態監聽器用注解配置來做進一步的簡化:
public class EventConfig { private Logger logger = LoggerFactory.getLogger(getClass()); (target = "UNPAID") public void create() { logger.info("訂單創建,待支付"); } (source = "UNPAID", target = "WAITING_FOR_RECEIVE") public void pay() { logger.info("用戶完成支付,待收貨"); } (source = "WAITING_FOR_RECEIVE", target = "DONE") public void receive() { logger.info("用戶已收貨,訂單完成"); } } |
上述代碼實現了與快速入門中定義的listener()方法創建的監聽器相同的功能,但是由于通過注解的方式配置,省去了原來事件監聽器中各種if的判斷,使得代碼顯得更為簡潔,擁有了更好的可讀性。
本文完整示例:
- 開源中國:http://git.oschina.net/didispace/SpringBoot-Learning/tree/master/Chapter6-1-1
- GitHub:https://github.com/dyc87112/SpringCloud-Learning/tree/master/1-Brixton%E7%89%88%E6%95%99%E7%A8%8B%E7%A4%BA%E4%BE%8B/Chapter6-1-1
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的使用Spring StateMachine框架实现状态机的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 复杂风控场景下,如何打造一款高效的规则引
- 下一篇: WSDM Cup 2019自然语言推理任