demand

When an order is placed, the user is notified of the success of the order

Create a Spring Boot project. The following dependencies are omitted

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
Copy the code

Create the event ApplicationEvent

@Getter
public class PushOrderEvent extends ApplicationEvent {

    private String orderNo;

    private Long userId;

    public PushOrderEvent(Object source, String orderNo,Long userId) {
        super(source);
        this.orderNo = orderNo;
        this.userId = userId; }}Copy the code

Create a listener ApplicationListener

Implement interface mode
@Slf4j
@Component
public class PushOrderListener implements ApplicationListener<PushOrderEvent> {


    @Override
    public void onApplicationEvent(PushOrderEvent event) {

        log.info("{} User placed an order {}", event.getUserId(), event.getOrderNo()); }}Copy the code
Annotation way
@Slf4j
@Component
public class AnnotationPushOrderListener {

    @EventListener
    public void handler(PushOrderEvent event) {

        log.info("{} User placed an order {}", event.getUserId(), event.getOrderNo()); }}Copy the code

Publish event

@Slf4j
@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private ApplicationEventPublisher publisher;

    @PostMapping("push")
    public ResponseEntity pushOrder(a) {
        String orderNo = UUID.randomUUID().toString();

        // Publish events
        publisher.publishEvent(new PushOrderEvent(this, orderNo, 666666L));

        returnResponseEntity.ok(orderNo); }}Copy the code

test

Request interface

http://127.0.0.1:8080/order/push
Copy the code

As a result, console output

User 666666 placed an order 211F238E-7517-4786-83CA-057C64545C65Copy the code

The source code

Click here to