Spring event listener event (default mq)


foreword

The businesses in the project are inevitably interrelated, but we should try our best to achieve low coupling in the code. The common practice is to introduce mq as a means of loose coupling; in fact, the most common decoupling is the interface
, and MVC directly passes Interfaces (an agreed rule) call each other, which is a manifestation of decoupling;
there is also springbean aop, etc., that is, IOC is a scene of decoupling;

Usually mq is our choice, but when it is only for simple business scenarios of decoupling, there is no need to introduce mq at all, and events in spring can achieve decoupling~


1. What is an event?

Usage scenario One change has a large impact. If the code is written together, the coupling will be high. In this way, event or mq can be used to decouple

After the order is successful:
1 Deduction of inventory
2 Maintenance of personal information
3 Logistics information
4 Order flow
5 Product sales
6 …

event is provided by spring, in org.springframework.context.event it
consists of three parts:

  1. event
  2. event listener
  3. event release

2. Use steps

1. Event

Declare a class, just inherit ApplicationEvent, and then you can put a self-created carrier (Bom) for information transmission, this Bom is optional

public class DemoEvent extends ApplicationEvent {
    
    

    private Bom bom;

    public DemoEvent(Bom source) {
    
    
        super(source);
        this.bom = source;
    }

    public Bom getBom() {
    
    
        return bom;
    }
}

2. Event monitoring

There are two ways to listen to events: 1 Annotation 2 Implementing the ApplicationListener interface is actually the same meaning 3 Conditional filtering

  1. Annotations can monitor multiple classes at the same time
@Slf4j
@Component
public class DemoEventListener {
    
    

    @EventListener(classes = DemoEvent.class)
    public void listener(DemoEvent event) {
    
    
        log.info(JSONUtil.toJsonStr(event));
    }
}
  1. implement the interface
@Slf4j
@Component
public class DemoEventListener1 implements ApplicationListener<DemoEvent> {

    @Override
    public void onApplicationEvent(DemoEvent event) {
        log.info(JSONUtil.toJsonStr(event));
    }
}
  1. On the basis of annotations, filter again
@Slf4j
@Component
public class DemoEventListener2 {

    @EventListener(condition = "#root.event.bom.f4.equals('2')")
    public void listener(DemoEvent event) {
        log.info(JSONUtil.toJsonStr(event));
    }
}

Among them #root.event.bom.f4 is the condition
#root.event fixed
bom is the parameter name we customized in the event
f4 is one of the attribute names

You can also write:

@EventListener(condition = "#root.getEvent().getBom().getF4().equals('2')")
is better understood~

3. Publish events

make a test class


@SpringBootTest
class DemoEventListenerTest {

    @Autowired
    ApplicationEventPublisher applicationEventPublisher;

    @Test
    public void publishPersonSaveEvent(){
        Bom bom = new Bom();
        bom.setF4("12");;
        bom.setF6("12");
        DemoEvent demoEvent = new DemoEvent(bom);
        applicationEventPublisher.publishEvent(demoEvent);

        bom.setF4("2");;
        bom.setF6("12");
        applicationEventPublisher.publishEvent(new DemoEvent(bom));
    }
}

3. Test results

result

It can be seen that both listening classes have received the message content published by the ApplicationEventPublisher publisher;
but DemoEventListener2 only received one message because it was filtered according to the conditions;


Summarize

For this simple business decoupling, we should give priority to the event event provided by spring, which can reduce the project expansion caused by the introduction of mq, and cause learning costs for unfamiliar personnel, which is conducive to the rapid advancement of the project; but when complex
business , or there are similar scenarios where other project businesses need to be decoupled in the same way, it is still mainly to introduce mq, depending on the appropriate scenario, take what you need;

Event can realize one-to-many. In the example in this article, one message
can be consumed and processed in multiple places to realize many-to-one. The annotation in this article can listen to multiple events at the same time @EventListener(classes = {A.class, B.class})
event supports things, when event processing fails, it will roll back

Guess you like

Origin blog.csdn.net/qq_32419139/article/details/132289445