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狀態的遷移。
創建狀態機配置類:
import com.demo1.app.states.Events; import com.demo1.app.states.States; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.statemachine.config.EnableStateMachine; import org.springframework.statemachine.config.EnumStateMachineConfigurerAdapter; import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer; import org.springframework.statemachine.config.builders.StateMachineStateConfigurer; import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer; import org.springframework.statemachine.listener.StateMachineListener; import org.springframework.statemachine.listener.StateMachineListenerAdapter; import org.springframework.statemachine.transition.Transition; import java.util.EnumSet; /** * 創建狀態機配置類 * @EnableStateMachine 注解用來啟用 Spring StateMachine狀態機功能 */ @Configuration @EnableStateMachine public class StateMachineConfig extends EnumStateMachineConfigurerAdapter<States, Events> { private Logger logger = LoggerFactory.getLogger(getClass()); /** * configure(StateMachineStateConfigurer<States, Events> states)方法用來初始化當前狀態機擁有哪些狀態, * 其中initial(States.UNPAID)定義了初始狀態為待支付UNPAID, * states(EnumSet.allOf(States.class))則指定了使用上一步中定義的所有狀態作為該狀態機的狀態定義。 * @param states * @throws Exception */ @Override public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception { states .withStates() .initial(States.UNPAID) //初始狀態 定義了初始狀態為待支付UNPAID, .states(EnumSet.allOf(States.class)); //則指定了使用上一步中定義的所有狀態作為該狀態機的狀態定義。 } /** * configure(StateMachineTransitionConfigurer<States, Events> transitions)方法用來初始化當前狀態機有哪些狀態遷移動作, * 其中命名中我們很容易理解每一個遷移動作,都有來源狀態source,目標狀態target以及觸發事件event。 * @param transitions StateMachineTransitionConfigurer<States, Events> * @throws Exception */ @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); } // * configure(StateMachineConfigurationConfigurer<States, Events> config)方法為當前的狀態機指定了狀態監聽器, // * 其中listener()則是調用了下一個內容創建的監聽器實例, // * 用來處理各個各個發生的狀態遷移事件。 // * @param config // * @throws Exception @Override public void configure(StateMachineConfigurationConfigurer<States, Events> config) throws Exception { config .withConfiguration() .listener(listener()); // 指定狀態機的處理監聽器 } // // * StateMachineListener<States, Events> listener()方法用來創建StateMachineListener狀態監聽器的實例, // * 在該實例中會定義具體的狀態遷移處理邏輯,上面的實現中只是做了一些輸出, // * 實際業務場景會有更復雜的邏輯,所以通常情況下, // * 我們可以將該實例的定義放到獨立的類定義中,並用注入的方式加載進來。 // * @return @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 { // 定義狀態機中的狀態 states .withStates() .initial(States.UNPAID) // 初始狀態 .states(EnumSet.allOf(States.class)); }
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)// 指定狀態來源和目標
.event(Events.PAY) // 指定觸發事件
.and()
.withExternal()
.source(States.WAITING_FOR_RECEIVE).target(States.DONE)
.event(Events.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)來完成收貨操作。在運行了上述程序之后,我們可以在控制台中獲得類似下面的輸出內容:

其中包括了狀態監聽器中對各個狀態遷移做出的處理。
通過上面的例子,我們可以對如何使用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的判斷,使得代碼顯得更為簡潔,擁有了更好的可讀性。
