使用状态机(Spring Statemachine)实现订单状态流转控制

在电商平台中,一个订单会有多种状态,临时单、已下单、待支付、已支付、待发货、待收货、已完成等等。每一种状态都和变化前的状态以及执行的操作有关。

比如,用户将商品加入购物车后,后台会生成一个所谓的“临时单”。因为用户还没有点击下单,所以这个订单实际上还没有生成。只有当用户下单后,这个“临时单”才会转化为一个“待支付的订单”。

以上过程中只有将一个处于“临时单”状态的订单执行下单操作,才能得到一个状态为“待支付”的订单。 即一个前置状态+一个恰当的操作,才能流转订单的状态。在这个过程中如果使用硬编码,我们就需要一系列的 if-else 语句来检查订单的当前状态、可执行操作以及这两个组合得到的下一个应该被流转的状态值。如果订单的状态流转很复杂,代码逻辑就会很复杂,可读性低,后期维护困难。

处理以上问题,我们可以使用状态设计模式来处理。对应到实践,就是状态机。

状态机是状态模式的一种应用,相当于上下文角色的一个升级版。在工作流或游戏等各种系统中有大量使用,如各种工作流引擎,它几乎是状态机的子集和实现,封装状态的变化规则。状态机可以帮助开发者简化状态控制的开发过程,让状态机结构更加层次化。

Spring 提供了一个很好的解决方案,Spring Statemachine(状态机)是应用程序开发人员在 Spring 应用程序中使用状态机概念的框架。

下面用 Spring 状态机模拟订单状态流转的过程,步骤如下。

1)添加依赖

  1. <dependency>
  2. <groupId>org.springframework.statemachine</groupId>
  3. <artifactId>spring-statemachine-core</artifactId>
  4. <version>2.0.1.RELEASE</version>
  5. </dependency>

2)创建订单实体类

  1. package net.biancheng.c.entity;
  2. public class Order {
  3. private int id;
  4. private OrderStatus status;
  5. public void setStatus(OrderStatus status) {
  6. this.status = status;
  7. }
  8. public OrderStatus getStatus() {
  9. return status;
  10. }
  11. public void setId(int id) {
  12. this.id = id;
  13. }
  14. public int getId() {
  15. return id;
  16. }
  17. @Override
  18. public String toString() {
  19. return "订单号:" + id + ", 订单状态:" + status;
  20. }
  21. }

3)创建订单状态枚举类和状态转换枚举类。

  1. package net.biancheng.c.utils;
  2. /**
  3. * 订单状态
  4. */
  5. public enum OrderStatus {
  6. // 待支付,待发货,待收货,已完成
  7. WAIT_PAYMENT, WAIT_DELIVER, WAIT_RECEIVE, FINISH;
  8. }
  9. package net.biancheng.c.utils;
  10. /**
  11. * 订单状态改变事件
  12. */
  13. public enum OrderStatusChangeEvent {
  14. // 支付,发货,确认收货
  15. PAYED, DELIVERY, RECEIVED;
  16. }

4)添加状态流配置

  1. package net.biancheng.c.utils;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.statemachine.StateMachineContext;
  5. import org.springframework.statemachine.StateMachinePersist;
  6. import org.springframework.statemachine.config.EnableStateMachine;
  7. import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
  8. import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
  9. import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
  10. import org.springframework.statemachine.persist.DefaultStateMachinePersister;
  11. import org.springframework.statemachine.support.DefaultStateMachineContext;
  12. import java.util.EnumSet;
  13. /**
  14. * 订单状态机配置
  15. */
  16. @Configuration
  17. @EnableStateMachine(name = "orderStateMachine")
  18. public class OrderStateMachineConfig extends StateMachineConfigurerAdapter<OrderStatus, OrderStatusChangeEvent> {
  19. /**
  20. * 配置状态
  21. *
  22. * @param states
  23. * @throws Exception
  24. */
  25. public void configure(StateMachineStateConfigurer<OrderStatus, OrderStatusChangeEvent> states) throws Exception {
  26. states
  27. .withStates()
  28. .initial(OrderStatus.WAIT_PAYMENT)
  29. .states(EnumSet.allOf(OrderStatus.class));
  30. }
  31. /**
  32. * 配置状态转换事件关系
  33. *
  34. * @param transitions
  35. * @throws Exception
  36. */
  37. public void configure(StateMachineTransitionConfigurer<OrderStatus, OrderStatusChangeEvent> transitions) throws Exception {
  38. transitions
  39. .withExternal().source(OrderStatus.WAIT_PAYMENT).target(OrderStatus.WAIT_DELIVER).event(OrderStatusChangeEvent.PAYED)
  40. .and()
  41. .withExternal().source(OrderStatus.WAIT_DELIVER).target(OrderStatus.WAIT_RECEIVE).event(OrderStatusChangeEvent.DELIVERY)
  42. .and()
  43. .withExternal().source(OrderStatus.WAIT_RECEIVE).target(OrderStatus.FINISH).event(OrderStatusChangeEvent.RECEIVED);
  44. }
  45. /**
  46. * 持久化配置
  47. * 实际使用中,可以配合redis等,进行持久化操作
  48. *
  49. * @return
  50. */
  51. @Bean
  52. public DefaultStateMachinePersister persister() {
  53. return new DefaultStateMachinePersister<>(new StateMachinePersist<Object, Object, Order>() {
  54. @Override
  55. public void write(StateMachineContext<Object, Object> context, Order order) throws Exception {
  56. //此处并没有进行持久化操作
  57. }
  58. @Override
  59. public StateMachineContext<Object, Object> read(Order order) throws Exception {
  60. //此处直接获取order中的状态,其实并没有进行持久化读取操作
  61. return new DefaultStateMachineContext(order.getStatus(), null, null, null);
  62. }
  63. });
  64. }
  65. }

5)添加订单状态监听器

  1. package net.biancheng.c.utils;
  2. import org.springframework.messaging.Message;
  3. import org.springframework.statemachine.annotation.OnTransition;
  4. import org.springframework.statemachine.annotation.WithStateMachine;
  5. import org.springframework.stereotype.Component;
  6. @Component("orderStateListener")
  7. @WithStateMachine(name = "orderStateMachine")
  8. public class OrderStateListenerImpl {
  9. @OnTransition(source = "WAIT_PAYMENT", target = "WAIT_DELIVER")
  10. public boolean payTransition(Message<OrderStatusChangeEvent> message) {
  11. Order order = (Order) message.getHeaders().get("order");
  12. order.setStatus(OrderStatus.WAIT_DELIVER);
  13. System.out.println("支付,状态机反馈信息:" + message.getHeaders().toString());
  14. return true;
  15. }
  16. @OnTransition(source = "WAIT_DELIVER", target = "WAIT_RECEIVE")
  17. public boolean deliverTransition(Message<OrderStatusChangeEvent> message) {
  18. Order order = (Order) message.getHeaders().get("order");
  19. order.setStatus(OrderStatus.WAIT_RECEIVE);
  20. System.out.println("发货,状态机反馈信息:" + message.getHeaders().toString());
  21. return true;
  22. }
  23. @OnTransition(source = "WAIT_RECEIVE", target = "FINISH")
  24. public boolean receiveTransition(Message<OrderStatusChangeEvent> message) {
  25. Order order = (Order) message.getHeaders().get("order");
  26. order.setStatus(OrderStatus.FINISH);
  27. System.out.println("收货,状态机反馈信息:" + message.getHeaders().toString());
  28. return true;
  29. }
  30. }

6)创建 OrderService 接口。

  1. package net.biancheng.c.service;
  2. import net.biancheng.c.entity.Order;
  3. import java.util.Map;
  4. public interface OrderService {
  5. //创建订单
  6. Order create();
  7. //发起支付
  8. Order pay(int id);
  9. //订单发货
  10. Order deliver(int id);
  11. //订单收货
  12. Order receive(int id);
  13. //获取所有订单信息
  14. Map<Integer, Order> getOrders();
  15. }

7)在 Service 业务逻辑中应用。

  1. package net.biancheng.c.serviceImpl;
  2. import net.biancheng.c.entity.Order;
  3. import net.biancheng.c.service.OrderService;
  4. import net.biancheng.c.utils.OrderStatus;
  5. import net.biancheng.c.utils.OrderStatusChangeEvent;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.messaging.Message;
  8. import org.springframework.messaging.support.MessageBuilder;
  9. import org.springframework.statemachine.StateMachine;
  10. import org.springframework.statemachine.persist.StateMachinePersister;
  11. import org.springframework.stereotype.Service;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. @Service("orderService")
  15. public class OrderServiceImpl implements OrderService {
  16. @Autowired
  17. private StateMachine<OrderStatus, OrderStatusChangeEvent> orderStateMachine;
  18. @Autowired
  19. private StateMachinePersister<OrderStatus, OrderStatusChangeEvent, Order> persister;
  20. private int id = 1;
  21. private Map<Integer, Order> orders = new HashMap<>();
  22. public Order create() {
  23. Order order = new Order();
  24. order.setStatus(OrderStatus.WAIT_PAYMENT);
  25. order.setId(id++);
  26. orders.put(order.getId(), order);
  27. return order;
  28. }
  29. public Order pay(int id) {
  30. Order order = orders.get(id);
  31. System.out.println("线程名称:" + Thread.currentThread().getName() + " 尝试支付,订单号:" + id);
  32. Message message = MessageBuilder.withPayload(OrderStatusChangeEvent.PAYED).setHeader("order", order).build();
  33. if (!sendEvent(message, order)) {
  34. System.out.println("线程名称:" + Thread.currentThread().getName() + " 支付失败, 状态异常,订单号:" + id);
  35. }
  36. return orders.get(id);
  37. }
  38. public Order deliver(int id) {
  39. Order order = orders.get(id);
  40. System.out.println("线程名称:" + Thread.currentThread().getName() + " 尝试发货,订单号:" + id);
  41. if (!sendEvent(MessageBuilder.withPayload(OrderStatusChangeEvent.DELIVERY).setHeader("order", order).build(), orders.get(id))) {
  42. System.out.println("线程名称:" + Thread.currentThread().getName() + " 发货失败,状态异常,订单号:" + id);
  43. }
  44. return orders.get(id);
  45. }
  46. public Order receive(int id) {
  47. Order order = orders.get(id);
  48. System.out.println("线程名称:" + Thread.currentThread().getName() + " 尝试收货,订单号:" + id);
  49. if (!sendEvent(MessageBuilder.withPayload(OrderStatusChangeEvent.RECEIVED).setHeader("order", order).build(), orders.get(id))) {
  50. System.out.println("线程名称:" + Thread.currentThread().getName() + " 收货失败,状态异常,订单号:" + id);
  51. }
  52. return orders.get(id);
  53. }
  54. public Map<Integer, Order> getOrders() {
  55. return orders;
  56. }
  57. /**
  58. * 发送订单状态转换事件
  59. *
  60. * @param message
  61. * @param order
  62. * @return
  63. */
  64. private synchronized boolean sendEvent(Message<OrderStatusChangeEvent> message, Order order) {
  65. boolean result = false;
  66. try {
  67. orderStateMachine.start();
  68. //尝试恢复状态机状态
  69. persister.restore(orderStateMachine, order);
  70. //添加延迟用于线程安全测试
  71. Thread.sleep(1000);
  72. result = orderStateMachine.sendEvent(message);
  73. //持久化状态机状态
  74. persister.persist(orderStateMachine, order);
  75. } catch (Exception e) {
  76. e.printStackTrace();
  77. } finally {
  78. orderStateMachine.stop();
  79. }
  80. return result;
  81. }
  82. }

8)编写客户端测试代码。

  1. import net.biancheng.c.service.OrderService;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.context.ConfigurableApplicationContext;
  5. @SpringBootApplication
  6. public class Test {
  7. public static void main(String[] args) {
  8. Thread.currentThread().setName("主线程");
  9. ConfigurableApplicationContext context = SpringApplication.run(Test.class, args);
  10. OrderService orderService = (OrderService) context.getBean("orderService");
  11. orderService.create();
  12. orderService.create();
  13. orderService.pay(1);
  14. new Thread("客户线程") {
  15. @Override
  16. public void run() {
  17. orderService.deliver(1);
  18. orderService.receive(1);
  19. }
  20. }.start();
  21. orderService.pay(2);
  22. orderService.deliver(2);
  23. orderService.receive(2);
  24. System.out.println("全部订单状态:" + orderService.getOrders());
  25. }
  26. }

运行结果如下。

...
线程名称:主线程 尝试支付,订单号:2
线程名称:客户线程 尝试发货,订单号:1
2020-11-10 09:42:59.528  INFO 10796 --- [            主线程] o.s.s.support.LifecycleObjectSupport     : started org.springframework.statemachine.support.DefaultStateMachineExecutor@eb507b9
2020-11-10 09:42:59.528  INFO 10796 --- [            主线程] o.s.s.support.LifecycleObjectSupport     : started FINISH WAIT_PAYMENT WAIT_RECEIVE WAIT_DELIVER  / WAIT_PAYMENT / uuid=5aa411ad-212a-4f2a-8afd-fc1009def5d5 / id=null
2020-11-10 09:42:59.528  INFO 10796 --- [            主线程] o.s.s.support.LifecycleObjectSupport     : stopped org.springframework.statemachine.support.DefaultStateMachineExecutor@eb507b9
2020-11-10 09:42:59.528  INFO 10796 --- [            主线程] o.s.s.support.LifecycleObjectSupport     : stopped FINISH WAIT_PAYMENT WAIT_RECEIVE WAIT_DELIVER  /  / uuid=5aa411ad-212a-4f2a-8afd-fc1009def5d5 / id=null
2020-11-10 09:42:59.528  INFO 10796 --- [            主线程] o.s.s.support.LifecycleObjectSupport     : started org.springframework.statemachine.support.DefaultStateMachineExecutor@eb507b9
2020-11-10 09:42:59.528  INFO 10796 --- [            主线程] o.s.s.support.LifecycleObjectSupport     : started FINISH WAIT_PAYMENT WAIT_RECEIVE WAIT_DELIVER  / WAIT_PAYMENT / uuid=5aa411ad-212a-4f2a-8afd-fc1009def5d5 / id=null
支付,状态机反馈信息:{order=订单号:2, 订单状态:WAIT_DELIVER, id=13bd1f00-21e1-cab4-3b2a-af8a4a82507a, timestamp=1604972579527}
...

由于运行结果篇幅过长,以上只贴出了部分运行结果。通过本节的真实业务案例,相信小伙伴们对状态模式已经有非常深刻的理解了

 

转载自 http://c.biancheng.net/view/8492.html

posted @ 2021-09-07 15:59  looyee  阅读(4172)  评论(0编辑  收藏  举报