Spring中组件StateMachine(状态机)状态模式实现订单状态流转控制

本文介绍了如何利用Spring的状态机组件来管理订单状态流转,包括添加相关依赖、定义订单实体类和状态枚举、配置状态转换、创建监听器以及服务实现。示例展示了从订单等待支付到订单结束的完整流程,并涉及状态监听和状态持久化的概念。
摘要由CSDN通过智能技术生成

Spring状态机流转订单状态

利用状态机实现订单状态流转控制

状态机是状态模式得一种运用,相当于上下文角色得一个升级。在工作流或游戏等各种系统中有大量使用,如工作流引擎,它几乎是状态机得子集和实现,封装状态得变化规则。spring也提供了我们一个很好的解决方案。Spring中的组件名称就叫StateMachine(状态机)。状态机帮助开发者简化状态控制的开发过程,让状态机结构更加层次化。

1 添加依赖

        <dependency>
            <groupId>org.springframework.statemachine</groupId>
            <artifactId>spring-statemachine-core</artifactId>
            <version>2.0.1.RELEASE</version>
        </dependency>

2 创建订单实体类

public class Order {
    @Getter
    @Setter
    private int id;
    @Getter
    @Setter
    private OrderStatus status;

    @Override
    public String toString() {
        return "订单号:" + id +", 订单状态:" + status;
    }
}

3 创建订单状态枚举类

public enum OrderStatus {

    /**
     * 待支付
     */
    WAIT_PAYMENT,

    /**
     * 待发货
     */
    WAIT_DELIVER,

    /**
     * 待收货
     */
    WAIT_RECEIVE,

    /**
     * 订单结束
     */
    FINISH;
}

4 创建状态转换枚举类

public enum OrderStatusChangeEvent {

    /**
     * 支付
     */
    PAYED,

    /**
     * 发货
     */
    DELIVERY,

    /**
     * 确认收货
     */
    RECEIVED;
}

5 添加状态流转配置

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yqq
 * @Date: 2023/07/16/21:49
 * @Description: 订单状态机配置
 */
@Configuration
@EnableStateMachine(name = "orderStateMachine")
public class OrderStateMachineConfig extends StateMachineConfigurerAdapter<OrderStatus,OrderStatusChangeEvent> {

    /**
     * 配置状态
     * @param states
     * @throws Exception
     */
    @Override
    public void configure(StateMachineStateConfigurer<OrderStatus, OrderStatusChangeEvent> states) throws Exception {
        states.withStates()
                .initial(OrderStatus.WAIT_PAYMENT)
                .states(EnumSet.allOf(OrderStatus.class));
    }

    /**
     * 配置状态转换事件关系
     * @param transitions
     * @throws Exception
     */
    @Override
    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);
            }
        });
    }
}

6 添加订单状态监听器

@Component
@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;
    }
}

7 创建IOrderService接口

public interface IOrderService {
    //创建新订单
    Order create();
    //发起支付
    Order pay(int id);
    //订单发货
    Order deliver(int id);
    //订单收货
    Order receive(int id);
    //获取所有订单信息
    Map<Integer,Order> getOrders();
}

8 创建Service实现类

@Service("orderService")
public class OrderServiceImpl implements IOrderService{

    @Autowired
    private StateMachine<OrderStatus,OrderStatusChangeEvent> orderStateMachine;
    @Autowired
    private StateMachinePersister<OrderStatus,OrderStatusChangeEvent,Order> persister;

    private int id = 1;
    private Map<Integer,Order> orders = new HashMap<>();

    @Override
    public Order create() {
        Order order = new Order();
        order.setStatus(OrderStatus.WAIT_PAYMENT);
        order.setId(id++);
        orders.put(order.getId(),order);
        return order;
    }

    @Override
    public Order pay(int id) {
        Order order = orders.get(id);
        System.out.println("线程名称:" + Thread.currentThread().getName() + " 尝试支付,订单号:" + id);
        Message<OrderStatusChangeEvent> message = MessageBuilder
                .withPayload(OrderStatusChangeEvent.PAYED)
                .setHeader("order", order)
                .build();
        if (!sendEvent(message,order)){
            System.out.println("线程名称:" + Thread.currentThread().getName() + " 支付失败,状态异常,订单号:" + id);
        }
        return orders.get(id);
    }

    @Override
    public Order deliver(int id) {
        Order order = orders.get(id);
        System.out.println("线程名称:" + Thread.currentThread().getName() + " 尝试发货,订单号:" + id);
        Message<OrderStatusChangeEvent> message = MessageBuilder
                .withPayload(OrderStatusChangeEvent.DELIVERY)
                .setHeader("order", order)
                .build();
        if (!sendEvent(message,order)){
            System.out.println("线程名称:" + Thread.currentThread().getName() + " 发货失败,状态异常,订单号:" + id);
        }
        return orders.get(id);
    }

    @Override
    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);
    }

    @Override
    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;
    }
}

9 测试

@SpringBootApplication
public class Test {
    public static void main(String[] args) {

        Thread.currentThread().setName("主线程");
        ConfigurableApplicationContext context = SpringApplication.run(Test.class,args);
        IOrderService orderService = (IOrderService)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());

    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

留不住的人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值