Moment For Technology

Complete guide to using Spring Events

Posted on Dec. 2, 2022, 1:05 p.m. by Lagan Rattan
Category: reading Tag: Spring Boot

instructions

This article uses Spring 4.2+ as an example, which was slightly different before this release. The author began to contact and use Spring Event since 2014, and developed jfinal-Event based on the Spring Event principle: gitee.com/596392912/J... JFinal Event 2.x is synchronized to Spring 4.2.x+. It is not necessary to create multiple Listener classes, which makes it easier to use.

use

Create an Event listener

In Spring 4.2+, you no longer need to write a separate listener class. You just need to mark the @EventListener annotation on the Spring Bean's methods.

Example: Multiple listeners that listen for Account creation and complete different business logic.

/** * Monitor the account and process the subsequent logic */ when the account is successfully created
@Component
public class AccountListener {

	/** * 1. Send email, SMS */
    @EventListener
    public void processAccountCreatedEvent1(AccountCreatedEvent event) {
        // TODO
    }

    /** * 2.@Order(100) is used to set the execution order */
    @EventListener
    @Order(100)
    public void processAccountCreatedEvent2(AccountCreatedEvent event) {
        // TODO
    }

    /** * 3.@AsyncUsed to mark the execution of */ in an asynchronous thread pool
    @EventListener
    @Async
    public void processAccountCreatedEvent3(AccountCreatedEvent event) {
        // TODO}}Copy the code

Send Event

Example: send account creation event in mybatis.

Note: If you are using JPA, JPA also has a corresponding event mechanism, which does not need to be handled manually as below.

Injected ApplicationEventPublisher * / / * * *
@Autowired
private ApplicationEventPublisher publisher;

@Override
public boolean save(Account account) {
	// False code, database saved successfully
	if (true) {
		publisher.publishEvent(new AccountCreatedEvent(account));
	}
	return false;
}
Copy the code

Quick jump button in IDEA

@EventListenerAttribute Description

@EventListener(value = {AccountCreatedEvent.class, AccountUpdatedEvent.class}, condition = "#event.account.age  10")
public void processAccountCreatedEvent2(AccountEvent event) {
	// TODO
}
Copy the code
  • valueclassesThe function is the same as that of a listener, which is used to support events of the same parent class in a method, for exampleAccountEvent;
  • conditionExpression, which supports Spring EL, for determining variables or methods in an event.

Listen execution order

The @order (100) annotation can be used to mark the Order of event listening execution, asynchronous case only ensure that the Order of listeners into the thread pool, the specific execution depends on the mood of the thread -.-

Listen for asynchronous execution

Use the @async flag. The prerequisite is that the @enableAsync command is used to enable Spring Async.

Spring Boot asynchronous configuration

This section is based on the asynchronous configuration in MICA.

Asynchronous configuration

  • @enableAsync Enabling async.
  • @enablescheduling Starts scheduled tasks.
  • MicaAsyncProperties Configuration for asynchronous thread pools.

Asynchronous Configuration Items



Configuration items The default value instructions
mica.async.core-pool-size 2 Number of asynchronous core threads. Default: 2
mica.async.keep-alive-seconds 300 Thread lifetime. Default: 300
mica.async.max-pool-size 50 Maximum number of asynchronous threads. Default: 50
mica.async.queue-capacity 10000 Queue capacity. Default: 10000

Open source is recommended

  • micaSpring Boot microservices core component set:Gitee.com/596392912/m...
  • AvueA magical framework based on vUE configurable:Gitee.com/smallweigit...
  • pigThe most powerful Microservice in the Universe (essential for architects) :gitee.com/log4j/pig
  • SpringBladeComplete online solution (necessary for enterprise development) :Gitee.com/smallc/Spri...
  • IJPayPayment SDK makes payment within reach:Gitee.com/javen205/IJ...

Pay attention to our

Scan the qr code above, more exciting content recommended every day!

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.