java状态机实现订单状态转移

news/2024/11/14 15:41:33/

一、状态机

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

二、状态机要素

把状态机的要素分为4个要素,即:现态、条件、动作、次态。
“现态”和“条件”是因,“动作”和“次态”是果。

(1)现态:是指当前所处状态;
(2)条件:又称为“事件”。当条件被满足时,将会触发一个动作,或者执行一次状态的迁移。
(3)动作:条件满足后执行的动作。动作不是必须的,当条件满足后,也可以不执行任何动作,直接迁移到新状态。
(4)次态:条件满足后要迁移往的新状态。“次态”是相对于“现态”而言的,“次态”一旦被激活,就转变成新的“现态”了。

三、状态机状态举例

以电商平台的订单状态为例,订单状态的可能有待支付、待发货、待收货、已完成、取消等。每一种状态都和变化前的状态以及执行的操作有关。

状态机图为:

 四、代码步骤

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

1.添加依赖

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

2.创建订单实体类

package com.sky.statemachinedemo.entity;import lombok.Data;/*** 订单实体类*/
@Data
public class Order {private Integer id;private Integer status;
}

3.创建订单状态枚举类

package com.sky.statemachinedemo.constants;/*** 订单状态枚举*/
public enum OrderStatusEnum {/*** 待付款*/WAIT_PAYMENT(0),/*** 待发货*/WAIT_DELIVER(1),/*** 待收货*/WAIT_RECEIVE(2),/*** 已完成*/FINISH(3),/*** 取消*/CANCEL(4),;/*** 订单状态*/public final int value;OrderStatusEnum(int value) {this.value = value;}public static Object getByValue(Integer status) {for(OrderStatusEnum OrderStatusEnum:OrderStatusEnum.values()){if(OrderStatusEnum.value==status){return OrderStatusEnum;}}return null;}
}

4.创建状态转换枚举类(事件event)

package com.sky.statemachinedemo.constants;/*** 状态转换枚举类(事件)*/
public enum OrderStatusChangeEvent {// 支付,发货,确认收货PAYED, DELIVERY, RECEIVED,CANCEL;
}

5.添加状态流配置

package com.sky.statemachinedemo.config;import com.sky.statemachinedemo.constants.OrderStatusChangeEvent;
import com.sky.statemachinedemo.constants.OrderStatusEnum;
import com.sky.statemachinedemo.entity.Order;
import lombok.extern.slf4j.Slf4j;
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.EnumStateMachineConfigurerAdapter;
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;/*** 订单状态机配置*/
@Slf4j
@Configuration
@EnableStateMachine(name = "OrderStateMachine")
public class OrderStateMachineConfig extends EnumStateMachineConfigurerAdapter<OrderStatusEnum, OrderStatusChangeEvent> {/*** 配置状态** @param states* @throws Exception*/public void configure(StateMachineStateConfigurer<OrderStatusEnum, OrderStatusChangeEvent> states) throws Exception {states.withStates().initial(OrderStatusEnum.WAIT_PAYMENT).states(EnumSet.allOf(OrderStatusEnum.class));}/*** 配置状态转换事件关系** @param transitions* @throws Exception*/public void configure(StateMachineTransitionConfigurer<OrderStatusEnum, OrderStatusChangeEvent> transitions) throws Exception {transitions.withExternal().source(OrderStatusEnum.WAIT_PAYMENT).target(OrderStatusEnum.WAIT_DELIVER).event(OrderStatusChangeEvent.PAYED).and().withExternal().source(OrderStatusEnum.WAIT_PAYMENT).target(OrderStatusEnum.CANCEL).event(OrderStatusChangeEvent.CANCEL).and().withExternal().source(OrderStatusEnum.WAIT_DELIVER).target(OrderStatusEnum.WAIT_RECEIVE).event(OrderStatusChangeEvent.DELIVERY).and().withExternal().source(OrderStatusEnum.WAIT_RECEIVE).target(OrderStatusEnum.FINISH).event(OrderStatusChangeEvent.RECEIVED);}/*** 持久化配置* 实际使用中,可以配合redis等,进行持久化操作** @return*/@Beanpublic DefaultStateMachinePersister persister() {return new DefaultStateMachinePersister<>(new StateMachinePersist<OrderStatusEnum, OrderStatusChangeEvent, Order>() {@Overridepublic void write(StateMachineContext<OrderStatusEnum, OrderStatusChangeEvent> context, Order Order) throws Exception {//此处并没有进行持久化操作//此处可调用更新状态流转接口(如:更新时间)状态不需要在此进行调用}@Overridepublic StateMachineContext<OrderStatusEnum, OrderStatusChangeEvent> read(Order Order) throws Exception {//此处直接获取Order中的状态,其实并没有进行持久化读取操作//实际生产中我们会查询出订单信息,根据订单状态获取状态机状态return new DefaultStateMachineContext(OrderStatusEnum.getByValue(Order.getStatus()), null, null, null);}});}
}

6.添加订单状态监听器 

package com.sky.statemachinedemo.listener;import com.sky.statemachinedemo.constants.OrderStatusChangeEvent;
import com.sky.statemachinedemo.constants.OrderStatusEnum;
import com.sky.statemachinedemo.entity.Order;
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 OrderStateListener {@OnTransition(source = "WAIT_PAYMENT", target = "WAIT_DELIVER")public boolean payTransition(Message<OrderStatusChangeEvent> message) {Order Order = (Order) message.getHeaders().get("order");Order.setStatus(OrderStatusEnum.WAIT_DELIVER.value);System.out.println("支付,状态机反馈信息:" + message.getHeaders().toString());return true;}@OnTransition(source = "WAIT_PAYMENT", target = "CANCEL")public boolean cancelTransition(Message<OrderStatusChangeEvent> message) {Order Order = (Order) message.getHeaders().get("order");Order.setStatus(OrderStatusEnum.CANCEL.value);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(OrderStatusEnum.WAIT_RECEIVE.value);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(OrderStatusEnum.FINISH.value);System.out.println("收货,状态机反馈信息:" + message.getHeaders().toString());return true;}
}

此处也可以单独添加监听,比如:

 

package com.sky.statemachinedemo.listener;import com.sky.statemachinedemo.constants.OrderStatusChangeEvent;
import com.sky.statemachinedemo.constants.OrderStatusEnum;
import com.sky.statemachinedemo.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.action.Action;
import org.springframework.stereotype.Component;@Slf4j
@Component
public class FinishListener implements Action<OrderStatusEnum, OrderStatusChangeEvent> {@Overridepublic void execute(StateContext<OrderStatusEnum, OrderStatusChangeEvent> stateContext) {Order Order = (Order) stateContext.getMessage().getHeaders().get("order");Order.setStatus(OrderStatusEnum.FINISH.value);System.out.println("收货,状态机反馈信息:" + stateContext.getMessage().getHeaders().toString());}
}

config修改:

    /*** 配置状态转换事件关系** @param transitions* @throws Exception*/public void configure(StateMachineTransitionConfigurer<OrderStatusEnum, OrderStatusChangeEvent> transitions) throws Exception {transitions.withExternal().source(OrderStatusEnum.WAIT_PAYMENT).target(OrderStatusEnum.WAIT_DELIVER).event(OrderStatusChangeEvent.PAYED).and().withExternal().source(OrderStatusEnum.WAIT_PAYMENT).target(OrderStatusEnum.CANCEL).event(OrderStatusChangeEvent.CANCEL).and().withExternal().source(OrderStatusEnum.WAIT_DELIVER).target(OrderStatusEnum.WAIT_RECEIVE).event(OrderStatusChangeEvent.DELIVERY).and().withExternal().source(OrderStatusEnum.WAIT_RECEIVE).target(OrderStatusEnum.FINISH).event(OrderStatusChangeEvent.RECEIVED).action(finishListener,transitionExceptionListener);}

 

7.创建OrderService接口

package com.sky.statemachinedemo.service;import com.sky.statemachinedemo.entity.Order;import java.util.Map;public interface OrderService {//创建订单Order create();//发起支付Order pay(Integer id);//发起支付Order cancel(Integer id);//订单发货Order deliver(Integer id);//订单收货Order receive(Integer id);//获取所有订单信息//模拟数据存储的订单信息,生产中用数据库存储Map<Integer, Order> getOrders();
}

8.在 Service 业务逻辑中应用

package com.sky.statemachinedemo.service;import com.sky.statemachinedemo.constants.OrderStatusChangeEvent;
import com.sky.statemachinedemo.constants.OrderStatusEnum;
import com.sky.statemachinedemo.entity.Order;
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
public class OrderServiceImpl implements OrderService{@Autowiredprivate StateMachine<OrderStatusEnum, OrderStatusChangeEvent> orderStateMachine;@Autowiredprivate StateMachinePersister<OrderStatusEnum, OrderStatusChangeEvent, Order> persister;private int id = 1;private Map<Integer, Order> orders = new HashMap<>();@Overridepublic Order create() {Order order = new Order();order.setStatus(OrderStatusEnum.WAIT_PAYMENT.value);order.setId(id++);orders.put(order.getId(), order);return order;}@Overridepublic Order pay(Integer 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);}@Overridepublic Order cancel(Integer id) {Order order = orders.get(id);System.out.println("线程名称:" + Thread.currentThread().getName() + " 尝试取消,订单号:" + id);Message message = MessageBuilder.withPayload(OrderStatusChangeEvent.CANCEL).setHeader("order", order).build();if (!sendEvent(message, order)) {System.out.println("线程名称:" + Thread.currentThread().getName() + " 取消失败, 状态异常,订单号:" + id);}return orders.get(id);}@Overridepublic Order deliver(Integer 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);}@Overridepublic Order receive(Integer 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);}@Overridepublic 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.编写单元测试代码

package com.sky.statemachinedemo.service;import com.sky.statemachinedemo.StateMachineDemoApplication;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest(classes = StateMachineDemoApplication.class,webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class OrderServiceTest extends TestCase {@AutowiredOrderService orderService;@Testpublic void stateTest(){orderService.create();orderService.pay(1);orderService.deliver(1);orderService.receive(1);orderService.cancel(1);}
}

10.也可以用controller测试,更方便

package com.sky.statemachinedemo.controller;import com.sky.statemachinedemo.entity.Order;
import com.sky.statemachinedemo.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/order")
public class OrderController {@AutowiredOrderService orderService;@RequestMapping("/create")public Order create(){return orderService.create();}@RequestMapping("/cancel")public Order cancel(Integer orderId){return orderService.cancel(orderId);}@RequestMapping("/pay")public Order pay(Integer orderId){return orderService.pay(orderId);}@RequestMapping("/deliver")public Order deliver(Integer orderId){return orderService.deliver(orderId);}@RequestMapping("/receive")public Order receive(Integer orderId){return orderService.receive(orderId);}
}


http://www.ppmy.cn/news/62915.html

相关文章

Spring中@Async用法总结(IT枫斗者)

Spring中Async用法总结(IT枫斗者) 引言 在Java应用中&#xff0c;绝大多数情况下都是通过同步的方式来实现交互处理的&#xff0c;但是在处理与第三方系统交互的时候&#xff0c;容易造成响应迟缓的情况&#xff0c;之前大部分都是使用多线程来完成此类任务&#xff0c;其实&…

【Python入门】字符串的扩展

前言 &#x1f4d5;作者简介&#xff1a;热爱跑步的恒川&#xff0c;致力于C/C、Java、Python等多编程语言&#xff0c;热爱跑步&#xff0c;喜爱音乐的一位博主。 &#x1f4d7;本文收录于Python零基础入门系列&#xff0c;本专栏主要内容为Python基础语法、判断、循环语句、函…

第一章 程序设计基本方法

文章目录 第一章 程序设计基本方法1 程序设计语言1.1 程序设计语言1.2 编译和解释1.3 计算机编程1、为什么学习编程&#xff1f;2、编程 2 Python语言概述2.1 Python语言的发展2.2 Python最小程序 3 Python开发环境配置3.1 Python开发环境安装1、打开官网下载2、运行安装包 3.2…

Java基础--->基础部分(2)【Java值传递】

文章目录 Java 值传递基本类型参数的传递引用类型参数的传递1引用类型参数的传递2问什么不引入引用传值呢&#xff1f; Java 值传递 Java 中的值传递主要使用的参数有形参和实参 实参定义的参数&#xff0c;已经实际存在可以直接拿来使用 形参指的是在使用函数时需要传递进函数…

MQ(面试问题简析)学习笔记

文章目录 1. 为什么使用消息队列2. 消息队列有什么优缺点3. Kafka、ActiveMQ、RabbitMQ、RocketMQ 有什么优缺点&#xff1f;4. 如何保证消息队列的高可用4.1 RabbitMQ 的高可用性4.2 Kafka 的高可用性 5. 如何保证消息不被重复消费&#xff08;如何保证消息消费的幂等性&#…

从不同视角来看待API数据接口

一、作为产品经理向客户推广API数据接口&#xff0c;需要注意以下几点&#xff1a; 1.了解目标客户&#xff1a;在推广API数据接口之前&#xff0c;首先需要了解目标客户的需求和痛点&#xff0c;针对客户的实际情况提供更具体化的解决方案。 2.强调API接口的价值&#xff1a…

浅谈线程池

浅谈线程池 1、线程池 1.1、线程池介绍 线程池是一种多线程处理形式&#xff0c;处理过程中将任务添加到队列&#xff0c;然后在创建线程后自动启动这些任务。线程池线程都是后台线程。每个线程都使用默认的堆栈大小&#xff0c;以默认的优先级运行&#xff0c;并处于多线程…

物联网|蓝牙4.0BLE协议栈简介|IAR集成开发环境简介|IAR各版本下载链接|物联网之蓝牙4.0 BLE基础-学习笔记(2)

文章目录 3、蓝牙4.0BLE协议栈简介Tips: BLE协议结构图介绍Tips IAR各版本下载链接 3、蓝牙4.0BLE协议栈简介 问题: 1、什么是LE协议栈?BLE协识栈与BLE协议的关系&#xff1f; 协议&#xff1a;机器之间的通讯标准&#xff0c;定义了一系列的通信标准&#xff0c;通信双方都按…