Java架构师-十项全能学习笔记(1)
@Configuration
@EnableStateMachine
public class OrderStateMachineConfig extends EnumStateMachineConfigurerAdapter<OrderState, OrderEvent> {
@Override
public void configure(StateMachineStateConfigurer<OrderState, OrderEvent> states) throws Exception {
states.withStates()
.initial(OrderState.CREATED)
.states(EnumSet.allOf(OrderState.class));
}
@Override
public void configure(StateMachineTransitionConfigurer<OrderState, OrderEvent> transitions) throws Exception {
transitions
.withExternal()
.source(OrderState.CREATED)
.target(OrderState.PENDING_PAYMENT)
.event(OrderEvent.PLACE_ORDER)
.and().withExternal()
.source(OrderState.PENDING_PAYMENT)
.target(OrderState.PENDING_DELIVERY)
.event(OrderEvent.PAID)
.and().withExternal()
.source(OrderState.PENDING_DELIVERY)
.target(OrderState.ORDER_COMPLETE)
.event(OrderEvent.DELIVERED);
}
}
@WithStateMachine
@Slf4j
@Data
public class OrderListener {
private String orderStatus = OrderState.CREATED.name();
@OnTransition(target = "PENDING_PAYMENT")
public void pendingPayment(Message message) {
log.info("订单创建,等待付款, status={} header={}",
OrderState.PENDING_PAYMENT.name(),
message.getHeaders().get("orderId"));
// TODO 模拟业务流程
setOrderStatus(OrderState.PENDING_PAYMENT.name());
}
@OnTransition(target = "PENDING_DELIVERY")
public void pendingDelivery() {
log.info("订单已付款,等待发货, status={} ",
OrderState.PENDING_DELIVERY.name());
// TODO 模拟业务流程
setOrderStatus(OrderState.PENDING_DELIVERY.name());
}
@OnTransition(target = "ORDER_COMPLETE")
public void complete() {
log.info("订单完成, status={}",
OrderState.ORDER_COMPLETE.name());
// TODO 模拟业务流程
setOrderStatus(OrderState.ORDER_COMPLETE.name());
}
}
public class MyRunner implements CommandLineRunner {
@Resource
StateMachine<OrderState, OrderEvent> stateMachine;
@Override
public void run(String... args) throws Exception {
stateMachine.start();
Message message = MessageBuilder
.withPayload(OrderEvent.PLACE_ORDER)
.setHeader("orderId", "998")
.build();
stateMachine.sendEvent(message);
stateMachine.sendEvent(OrderEvent.PAID);
stateMachine.sendEvent(OrderEvent.DELIVERED);
}
}
@SpringBootApplication
public class ApplicationStarter {
@Bean
public MyRunner chickenRun() {
return new MyRunner();
}
public static void main(String[] arg) {
SpringApplication.run(ApplicationStarter.class, arg);
}
}