Spring Boot 2.x實戰(zhàn)之StateMachine

本文首發(fā)于個人網(wǎng)站:Spring Boot 2.x實戰(zhàn)之StateMachine

Spring StateMachine是一個狀態(tài)機框架,在Spring框架項目中,開發(fā)者可以通過簡單的配置就能獲得一個業(yè)務狀態(tài)機,而不需要自己去管理狀態(tài)機的定義、初始化等過程。今天這篇文章,我們通過一個案例學習下Spring StateMachine框架的用法。

案例介紹

假設在一個業(yè)務系統(tǒng)中,有這樣一個對象,它有三個狀態(tài):草稿、待發(fā)布、發(fā)布完成,針對這三個狀態(tài)的業(yè)務動作也比較簡單,分別是:上線、發(fā)布、回滾。該業(yè)務狀態(tài)機如下圖所示。

img

實戰(zhàn)

接下來,基于上面的業(yè)務狀態(tài)機進行Spring StateMachine的演示。

  • 創(chuàng)建一個基礎的Spring Boot工程,在主pom文件中加入Spring StateMachine的依賴:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>online.javaadu</groupId>
  <artifactId>statemachinedemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>statemachinedemo</name>
  <description>Demo project for Spring Boot</description>

  <properties>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>org.junit.vintage</groupId>
          <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <!--加入spring statemachine的依賴-->
        <dependency>
        <groupId>org.springframework.statemachine</groupId>
        <artifactId>spring-statemachine-core</artifactId>
        <version>2.1.3.RELEASE</version>
      </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>

定義狀態(tài)枚舉和事件枚舉,代碼如下:

/**
* 狀態(tài)枚舉
**/
public enum States {
    DRAFT,
    PUBLISH_TODO,
    PUBLISH_DONE,
}

/**
* 事件枚舉
**/
public enum Events {
    ONLINE,
    PUBLISH,
    ROLLBACK
}
  • 完成狀態(tài)機的配置,包括:(1)狀態(tài)機的初始狀態(tài)和所有狀態(tài);(2)狀態(tài)之間的轉(zhuǎn)移規(guī)則
@Configuration
@EnableStateMachine
public class StateMachineConfig extends EnumStateMachineConfigurerAdapter<States, Events> {

    @Override
    public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception {
        states.withStates().initial(States.DRAFT).states(EnumSet.allOf(States.class));
    }

    @Override
    public void configure(StateMachineTransitionConfigurer<States, Events> transitions) throws Exception {
        transitions.withExternal()
            .source(States.DRAFT).target(States.PUBLISH_TODO)
            .event(Events.ONLINE)
            .and()
            .withExternal()
            .source(States.PUBLISH_TODO).target(States.PUBLISH_DONE)
            .event(Events.PUBLISH)
            .and()
            .withExternal()
            .source(States.PUBLISH_DONE).target(States.DRAFT)
            .event(Events.ROLLBACK);
    }
}
  • 定義一個測試業(yè)務對象,狀態(tài)機的狀態(tài)轉(zhuǎn)移都會反映到該業(yè)務對象的狀態(tài)變更上
@WithStateMachine
@Data
@Slf4j
public class BizBean {

    /**
     * @see States
     */
    private String status = States.DRAFT.name();

    @OnTransition(target = "PUBLISH_TODO")
    public void online() {
        log.info("操作上線,待發(fā)布. target status:{}", States.PUBLISH_TODO.name());
        setStatus(States.PUBLISH_TODO.name());
    }

    @OnTransition(target = "PUBLISH_DONE")
    public void publish() {
        log.info("操作發(fā)布,發(fā)布完成. target status:{}", States.PUBLISH_DONE.name());
        setStatus(States.PUBLISH_DONE.name());
    }

    @OnTransition(target = "DRAFT")
    public void rollback() {
        log.info("操作回滾,回到草稿狀態(tài). target status:{}", States.DRAFT.name());
        setStatus(States.DRAFT.name());
    }

}
  • 編寫測試用例,這里我們使用CommandLineRunner接口代替,定義了一個StartupRunner,在該類的run方法中啟動狀態(tài)機、發(fā)送不同的事件,通過日志驗證狀態(tài)機的流轉(zhuǎn)過程。
public class StartupRunner implements CommandLineRunner {

    @Resource
    StateMachine<States, Events> stateMachine;

    @Override
    public void run(String... args) throws Exception {
        stateMachine.start();
        stateMachine.sendEvent(Events.ONLINE);
        stateMachine.sendEvent(Events.PUBLISH);
        stateMachine.sendEvent(Events.ROLLBACK);
    }
}

在運行上述程序后,我們可以在控制臺中獲得如下輸出,我們執(zhí)行了三個操作:上線、發(fā)布、回滾,在下圖中也確實看到了對應的日志。不過我還發(fā)現(xiàn)有一個意料之外的地方——在啟動狀態(tài)機的時候,還打印出了一個日志——“操作回滾,回到草稿狀態(tài). target status:DRAFT”,這里應該是狀態(tài)機設置初始狀態(tài)的時候觸發(fā)的。

image-20191110162618938

分析

如上面的實戰(zhàn)過程所示,使用Spring StateMachine的步驟如下:

  1. 定義狀態(tài)枚舉和事件枚舉
  2. 定義狀態(tài)機的初始狀態(tài)和所有狀態(tài)
  3. 定義狀態(tài)之間的轉(zhuǎn)移規(guī)則
  4. 在業(yè)務對象中使用狀態(tài)機,編寫響應狀態(tài)變化的監(jiān)聽器方法

為了將狀態(tài)變更的操作都統(tǒng)一管理起來,我們會考慮在項目中引入狀態(tài)機,這樣其他的業(yè)務模塊就和狀態(tài)轉(zhuǎn)移模塊隔離開來了,其他業(yè)務模塊也不會糾結(jié)于當前的狀態(tài)是什么,應該做什么操作。在應用狀態(tài)機實現(xiàn)業(yè)務需求時,關鍵是業(yè)務狀態(tài)的分析,只要狀態(tài)機設計得沒問題,具體的實現(xiàn)可以選擇用Spring StateMachine,也可以自己去實現(xiàn)一個狀態(tài)機。

使用Spring StateMachine的好處在于自己無需關心狀態(tài)機的實現(xiàn)細節(jié),只需要關心業(yè)務有什么狀態(tài)、它們之間的轉(zhuǎn)移規(guī)則是什么、每個狀態(tài)轉(zhuǎn)移后真正要進行的業(yè)務操作。

本文完整實例參見:https://github.com/duqicauc/Spring-Boot-2.x-In-Action/tree/master/statemachinedemo

參考資料

  1. http://blog.didispace.com/spring-statemachine/
  2. https://projects.spring.io/spring-statemachine/#quick-start

本號專注于后端技術、JVM問題排查和優(yōu)化、Java面試題、個人成長和自我管理等主題,為讀者提供一線開發(fā)者的工作和成長經(jīng)驗,期待你能在這里有所收獲。
javaadu
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容