Springboot+mechineState状态机
1、引入依赖
<dependency><groupId>org.springframework.statemachine</groupId><artifactId>spring-statemachine-core</artifactId><version>2.0.1.RELEASE</version>
</dependency>
2、订单的状态机配置类
/*** 订单状态机配置*/
@Configuration
@EnableStateMachine(name = "orderStateMachine")
public class OrderStateMachineConfig extends StateMachineConfigurerAdapter<OrderStatus, OrderStatusChangeEvent> {@Overridepublic void configure(StateMachineStateConfigurer<OrderStatus, OrderStatusChangeEvent> states) throws Exception {states.withStates().initial(OrderStatus.WAIT_PAYMENT).states(EnumSet.allOf(OrderStatus.class));}/*** 配置状态转换事件关系*/@Overridepublic 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等,进行持久化操作*/@Beanpublic StateMachinePersister<OrderStatus, OrderStatusChangeEvent, Order> persister(){return new DefaultStateMachinePersister<>(new StateMachinePersist<OrderStatus, OrderStatusChangeEvent, Order>() {@Overridepublic void write(StateMachineContext<OrderStatus, OrderStatusChangeEvent> context, Order order) throws Exception {//此处并没有进行持久化操作}@Overridepublic StateMachineContext<OrderStatus, OrderStatusChangeEvent> read(Order order) throws Exception {//此处直接获取order中的状态,其实并没有进行持久化读取操作return new DefaultStateMachineContext<>(order.getStatus(), null, null, null);}});}
}/*** 订单状态*/
public enum OrderStatus {WAIT_PAYMENT, WAIT_DELIVER, WAIT_RECEIVE, FINISH;
}
/*** 订单状态改变事件*/
public enum OrderStatusChangeEvent {PAYED, DELIVERY, RECEIVED;
}
3、添加状态变换监听
@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("支付 headers=" + 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("发货 headers=" + 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("收货 headers=" + message.getHeaders().toString());return true;}
}
5、放到业务类中调用
@Service("orderService")
public class OrderServiceImpl implements OrderService {@Autowiredprivate OrderMapper orderMapper;@Autowiredprivate StateMachine<OrderStatus, OrderStatusChangeEvent> orderStateMachine;@Autowiredprivate StateMachinePersister<OrderStatus, OrderStatusChangeEvent, Order> persister;private int id = 1;private Map<Integer, Order> orders = new HashMap<>();@Overridepublic Order creat() {Order order = new Order();order.setStatus(OrderStatus.WAIT_PAYMENT);order.setId(id++);orders.put(order.getId(), order);return order;}@Overridepublic Order pay(int id) {Order order = orders.get(id);System.out.println("threadName=" + Thread.currentThread().getName() + " 尝试支付 id=" + id);Message message = MessageBuilder.withPayload(OrderStatusChangeEvent.PAYED).setHeader("order", order).build();if (!sendEvent(message, order)) {System.out.println("threadName=" + Thread.currentThread().getName() + " 支付失败, 状态异常 id=" + id);}return orders.get(id);}@Overridepublic Order deliver(int id) {Order order = orders.get(id);System.out.println("threadName=" + Thread.currentThread().getName() + " 尝试发货 id=" + id);if (!sendEvent(MessageBuilder.withPayload(OrderStatusChangeEvent.DELIVERY).setHeader("order", order).build(), orders.get(id))) {System.out.println("threadName=" + Thread.currentThread().getName() + " 发货失败,状态异常 id=" + id);}return orders.get(id);}@Overridepublic Order receive(int id) {Order order = orders.get(id);System.out.println("threadName=" + Thread.currentThread().getName() + " 尝试收货 id=" + id);if (!sendEvent(MessageBuilder.withPayload(OrderStatusChangeEvent.RECEIVED).setHeader("order", order).build(), orders.get(id))) {System.out.println("threadName=" + Thread.currentThread().getName() + " 收货失败,状态异常 id=" + id);}return orders.get(id);}@Overridepublic Map<Integer, Order> getOrders() {return orders;}/*** 发送订单状态转换事件*/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;}
}
参考:https://docs.spring.io/spring-statemachine/docs/1.0.0.M3/reference/htmlsingle/#sm-statecontext
https://blog.csdn.net/u012129558/article/details/90519577