赞
踩
状态机是状态模式的一种应用,相当于上下文角色的一个升级版。在工作流或游戏等各种系统中有大量使用,如各种工作流引擎,它几乎是状态机的子集和实现,封装状态的变化规则。状态机可以帮助开发者简化状态控制的开发过程,让状态机结构更加层次化。Spring 提供了一个很好的解决方案,Spring Statemachine(状态机)是应用程序开发人员在 Spring 应用程序中使用状态机概念的框架。
状态机参考文档如下:
https://docs.spring.io/spring-statemachine/docs/3.0.1
在电商平台中,一个订单会有多种状态,临时单、已下单、待支付、已支付、待发货、待收货、已完成等等。每一种状态都和变化前的状态以及执行的操作有关。
比如,用户将商品加入购物车后,后台会生成一个所谓的“临时单”。因为用户还没有点击下单,所以这个订单实际上还没有生成。只有当用户下单后,这个“临时单”才会转化为一个“待支付的订单”。
以上过程中只有将一个处于“临时单”状态的订单执行下单操作,才能得到一个状态为“待支付”的订单。 即一个前置状态+一个恰当的操作,才能流转订单的状态。在这个过程中如果使用硬编码,我们就需要一系列的 if-else 语句来检查订单的当前状态、可执行操作以及这两个组合得到的下一个应该被流转的状态值。如果订单的状态流转很复杂,代码逻辑就会很复杂,可读性低,后期维护困难。这个时候我们就需要用到Spring状态机。
我们使用熟悉的spring enabler注释来简化配置。 有两个注解,@EnableStateMachine和@EnableStateMachineFactory。 这些注解如果放置在@Configuration类中,将启用状态机所需的一些基本功能。当配置想要创建一个StateMachine的实例时使用@EnableStateMachine。 通常@Configuration类扩展了适配器EnumStateMachineConfigurerAdapter或StateMachineConfigurerAdapter,它允许用户覆盖配置回调方法。 我们会自动检测用户是否正在使用这些适配器类并修改运行时配置逻辑。当配置想要创建StateMachineFactory的一个实例时使用@EnableStateMachineFactory。
@Configuration @EnableStateMachine public class Config1Enums extends EnumStateMachineConfigurerAdapter<States, Events> { @Override public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception { states .withStates() .initial(States.S1)//初始状态 .end(States.SF)//结束 .states(EnumSet.allOf(States.class));//状态枚举显示可能出现的状态 } }
支持三种不同类型的过渡,包括外部,内部和本地。 转换或者是由一个信号触发的,该信号是发送到状态机或计时器的事件。
@Configuration @EnableStateMachine public class Config3 extends EnumStateMachineConfigurerAdapter<States, Events> { @Override public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception { states .withStates() .initial(States.S1) .states(EnumSet.allOf(States.class)); } @Override public void configure(StateMachineTransitionConfigurer<States, Events> transitions) throws Exception { transitions .withExternal() .source(States.S1).target(States.S2) .event(Events.E1) .and() .withInternal() .source(States.S2) .event(Events.E2) .and() .withLocal() .source(States.S2).target(States.S3) .event(Events.E3); } }
1.添加依赖
<dependency>
<groupId>org.springframework.statemachine</groupId>
<artifactId>spring-statemachine-core</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
2.创建订单实体类
public class Order { private int id; private OrderStatus status; public void setStatus(OrderStatus status) { this.status = status; } public OrderStatus getStatus() { return status; } public void setId(int id) { this.id = id; } public int getId() { return id; } @Override public String toString() { return "订单号:" + id + ", 订单状态:" + status; } }
3.创建枚举类
/**
* 订单状态
*/
public enum OrderStatus {
// 待支付,待发货,待收货,已完成
WAIT_PAYMENT, WAIT_DELIVER, WAIT_RECEIVE, FINISH;
}
package net.biancheng.c.utils;
/**
* 订单状态改变事件
*/
public enum OrderStatusChangeEvent {
// 支付,发货,确认收货
PAYED, DELIVERY, RECEIVED;
}
4.状态流配置
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.statemachine.StateMachineContext; import org.springframework.statemachine.StateMachinePersist; import org.springframework.statemachine.config.EnableStateMachine; import org.springframework.statemachine.config.StateMachineConfigurerAdapter; import org.springframework.statemachine.config.builders.StateMachineStateConfigurer; import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer; import org.springframework.statemachine.persist.DefaultStateMachinePersister; import org.springframework.statemachine.support.DefaultStateMachineContext; import java.util.EnumSet; /** * 订单状态机配置 */ @Configuration @EnableStateMachine(name = "orderStateMachine") public class OrderStateMachineConfig extends StateMachineConfigurerAdapter<OrderStatus, OrderStatusChangeEvent> { /** * 配置状态 * * @param states * @throws Exception */ public void configure(StateMachineStateConfigurer<OrderStatus, OrderStatusChangeEvent> states) throws Exception { states .withStates() .initial(OrderStatus.WAIT_PAYMENT) .states(EnumSet.allOf(OrderStatus.class)); } /** * 配置状态转换事件关系 *由一个前状态+当前状态实现状态转换 .withExternal().source(OrderStatus.WAIT_PAYMENT).target(OrderStatus.WAIT_DELIVER).event(OrderStatusChangeEvent.PAYED) * @param transitions * @throws Exception */ public void configure(StateMachineTransitionConfigurer<OrderStatus, OrderStatusChangeEvent> transitions) throws Exception { transitions .withExternal().source(OrderStatus.WAIT_PAYMENT).target(OrderStatus.WAIT_DELIVER).event(OrderStatusChangeEvent.PAYED) .and() .withExternal().source(OrderStatus.WAIT_DELIVER).target(OrderStatus.WAIT_RECEIVE).event(OrderStatusChangeEvent.DELIVERY) .and() .withExternal().source(OrderStatus.WAIT_RECEIVE).target(OrderStatus.FINISH).event(OrderStatusChangeEvent.RECEIVED); } /** * 持久化配置 * 实际使用中,可以配合redis等,进行持久化操作 * * @return */ @Bean public DefaultStateMachinePersister persister() { return new DefaultStateMachinePersister<>(new StateMachinePersist<Object, Object, Order>() { @Override public void write(StateMachineContext<Object, Object> context, Order order) throws Exception { //此处并没有进行持久化操作 } @Override public StateMachineContext<Object, Object> read(Order order) throws Exception { //此处直接获取order中的状态,其实并没有进行持久化读取操作 return new DefaultStateMachineContext(order.getStatus(), null, null, null); } }); } }
5.添加状态变化监听器
import org.springframework.messaging.Message; import org.springframework.statemachine.annotation.OnTransition; import org.springframework.statemachine.annotation.WithStateMachine; import org.springframework.stereotype.Component; @Component("orderStateListener") @WithStateMachine(name = "orderStateMachine") public class OrderStateListenerImpl { @OnTransition(source = "WAIT_PAYMENT", target = "WAIT_DELIVER") public boolean payTransition(Message<OrderStatusChangeEvent> message) { Order order = (Order) message.getHeaders().get("order"); order.setStatus(OrderStatus.WAIT_DELIVER); System.out.println("支付,状态机反馈信息:" + message.getHeaders().toString()); return true; } @OnTransition(source = "WAIT_DELIVER", target = "WAIT_RECEIVE") public boolean deliverTransition(Message<OrderStatusChangeEvent> message) { Order order = (Order) message.getHeaders().get("order"); order.setStatus(OrderStatus.WAIT_RECEIVE); System.out.println("发货,状态机反馈信息:" + message.getHeaders().toString()); return true; } @OnTransition(source = "WAIT_RECEIVE", target = "FINISH") public boolean receiveTransition(Message<OrderStatusChangeEvent> message) { Order order = (Order) message.getHeaders().get("order"); order.setStatus(OrderStatus.FINISH); System.out.println("收货,状态机反馈信息:" + message.getHeaders().toString()); return true; } }
6.创建 OrderService 接口,并实现
import net.biancheng.c.entity.Order;
import java.util.Map;
public interface OrderService {
//创建订单
Order create();
//发起支付
Order pay(int id);
//订单发货
Order deliver(int id);
//订单收货
Order receive(int id);
//获取所有订单信息
Map<Integer, Order> getOrders();
}
import net.biancheng.c.entity.Order; import net.biancheng.c.service.OrderService; import net.biancheng.c.utils.OrderStatus; import net.biancheng.c.utils.OrderStatusChangeEvent; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; import org.springframework.statemachine.StateMachine; import org.springframework.statemachine.persist.StateMachinePersister; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; @Service("orderService") public class OrderServiceImpl implements OrderService { @Autowired private StateMachine<OrderStatus, OrderStatusChangeEvent> orderStateMachine; @Autowired private StateMachinePersister<OrderStatus, OrderStatusChangeEvent, Order> persister; private int id = 1; private Map<Integer, Order> orders = new HashMap<>(); public Order create() { Order order = new Order(); order.setStatus(OrderStatus.WAIT_PAYMENT); order.setId(id++); orders.put(order.getId(), order); return order; } public Order pay(int id) { Order order = orders.get(id); System.out.println("线程名称:" + Thread.currentThread().getName() + " 尝试支付,订单号:" + id); Message message = MessageBuilder.withPayload(OrderStatusChangeEvent.PAYED).setHeader("order", order).build(); if (!sendEvent(message, order)) { System.out.println("线程名称:" + Thread.currentThread().getName() + " 支付失败, 状态异常,订单号:" + id); } return orders.get(id); } public Order deliver(int id) { Order order = orders.get(id); System.out.println("线程名称:" + Thread.currentThread().getName() + " 尝试发货,订单号:" + id); if (!sendEvent(MessageBuilder.withPayload(OrderStatusChangeEvent.DELIVERY).setHeader("order", order).build(), orders.get(id))) { System.out.println("线程名称:" + Thread.currentThread().getName() + " 发货失败,状态异常,订单号:" + id); } return orders.get(id); } public Order receive(int id) { Order order = orders.get(id); System.out.println("线程名称:" + Thread.currentThread().getName() + " 尝试收货,订单号:" + id); if (!sendEvent(MessageBuilder.withPayload(OrderStatusChangeEvent.RECEIVED).setHeader("order", order).build(), orders.get(id))) { System.out.println("线程名称:" + Thread.currentThread().getName() + " 收货失败,状态异常,订单号:" + id); } return orders.get(id); } public Map<Integer, Order> getOrders() { return orders; } /** * 发送订单状态转换事件 * * @param message * @param order * @return */ private synchronized boolean sendEvent(Message<OrderStatusChangeEvent> message, Order order) { boolean result = false; try { orderStateMachine.start(); //尝试恢复状态机状态 persister.restore(orderStateMachine, order); //添加延迟用于线程安全测试 Thread.sleep(1000); result = orderStateMachine.sendEvent(message); //持久化状态机状态 persister.persist(orderStateMachine, order); } catch (Exception e) { e.printStackTrace(); } finally { orderStateMachine.stop(); } return result; } }
7.测试
import net.biancheng.c.service.OrderService; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class Test { public static void main(String[] args) { Thread.currentThread().setName("主线程"); ConfigurableApplicationContext context = SpringApplication.run(Test.class, args); OrderService orderService = (OrderService) context.getBean("orderService"); orderService.create(); orderService.create(); orderService.pay(1); new Thread("客户线程") { @Override public void run() { orderService.deliver(1); orderService.receive(1); } }.start(); orderService.pay(2); orderService.deliver(2); orderService.receive(2); System.out.println("全部订单状态:" + orderService.getOrders()); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。