Backend Development 9 min read

Using Spring Event for Synchronous and Asynchronous Processing in Spring Cloud Alibaba Projects

This article demonstrates how to create custom Spring events, define listeners, publish events, and enable asynchronous handling with @EnableAsync and @Async annotations, providing complete code examples and test results for both synchronous and asynchronous scenarios in a Spring Cloud Alibaba micro‑service environment.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Using Spring Event for Synchronous and Asynchronous Processing in Spring Cloud Alibaba Projects

The author introduces a Spring Cloud Alibaba video tutorial that covers middleware, OAuth2 authentication, gray release, and distributed transactions, then focuses on using Spring Event to decouple business logic.

Spring Event – Synchronous Usage

Spring Event (Application Event) implements the observer pattern, allowing one bean to notify others after completing a task.

1. Custom Event

Define an event class that extends ApplicationEvent :

/**
 * @author Strive
 * @date 2022/4/22 18:00
 * @description
 */
@Data
@ToString
public class OrderProductEvent extends ApplicationEvent {

  /** The information carried by this event */
  private String orderId;

  public OrderProductEvent(Object source, String orderId) {
    super(source);
    this.orderId = orderId;
  }
}

2. Listener Definition

Implement ApplicationListener or annotate a method with @EventListener :

/**
 * Implements ApplicationListener for OrderProductEvent
 */
@Slf4j
@Component
public class OrderProductListener implements ApplicationListener
{

  /** Handles the event */
  @SneakyThrows
  @Override
  public void onApplicationEvent(OrderProductEvent event) {
    String orderId = event.getOrderId();
    long start = System.currentTimeMillis();
    Thread.sleep(2000);
    long end = System.currentTimeMillis();
    log.info("{}:Check order product price took: ({}) ms", orderId, (end - start));
  }
}

3. Publisher Definition

Publish the event via ApplicationEventPublisher (in this case injected as ApplicationContext ):

@Slf4j
@Service
@RequiredArgsConstructor
public class OrderService {

  /** Inject ApplicationContext to publish events */
  private final ApplicationContext applicationContext;

  /** Place an order */
  public String buyOrder(String orderId) {
    long start = System.currentTimeMillis();
    // 1. Query order details
    // 2. Validate order price (synchronous)
    applicationContext.publishEvent(new OrderProductEvent(this, orderId));
    // 3. Send SMS (asynchronous)
    long end = System.currentTimeMillis();
    log.info("All tasks completed, total time: ({}) ms", end - start);
    return "Purchase successful";
  }
}

4. Unit Test

@SpringBootTest
public class OrderServiceTest {
  @Autowired
  private OrderService orderService;

  @Test
  public void buyOrderTest() {
    orderService.buyOrder("732171109");
  }
}

Test output shows the listener logging the time taken for price validation.

Spring Event – Asynchronous Usage

For scenarios like sending emails or SMS that do not need to block the request, the same event mechanism can be used asynchronously.

1. Custom Event

@Data
@AllArgsConstructor
public class MsgEvent {
  /** Message payload */
  public String orderId;
}

2. Listener with @EventListener

@Slf4j
@Component
public class MsgListener {

  @SneakyThrows
  @EventListener(MsgEvent.class)
  public void sendMsg(MsgEvent event) {
    String orderId = event.getOrderId();
    long start = System.currentTimeMillis();
    log.info("Develop sending SMS");
    log.info("Develop sending Email");
    Thread.sleep(4000);
    long end = System.currentTimeMillis();
    log.info("{}:Send SMS & Email took: ({}) ms", orderId, (end - start));
  }
}

3. Publisher (adds async event)

public String buyOrder(String orderId) {
  long start = System.currentTimeMillis();
  // 1. Query order details
  // 2. Validate price (synchronous)
  applicationContext.publishEvent(new OrderProductEvent(this, orderId));
  // 3. Send SMS & Email asynchronously
  applicationContext.publishEvent(new MsgEvent(orderId));
  long end = System.currentTimeMillis();
  log.info("All tasks completed, total time: ({}) ms", end - start);
  return "Purchase successful";
}

4. Enable Asynchronous Processing

Add @EnableAsync to the main application class and @Async to the asynchronous listener method.

@EnableAsync
@SpringBootApplication
public class MingYueSpringbootEventApplication {
  public static void main(String[] args) {
    SpringApplication.run(MingYueSpringbootEventApplication.class, args);
  }
}
@Async
@SneakyThrows
@EventListener(MsgEvent.class)
public void sendMsg(MsgEvent event) {
  // same implementation as above
}

Running the asynchronous test shows the main thread finishing while the task-1 thread logs the SMS and email sending after a delay.

Conclusion

The article encourages readers to like, share, and follow the author’s public account to obtain related PDF resources.

backendJavamicroservicesSpringasynchronousevent
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.