Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the difference between EventBus and SpringEvent

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

What is the difference between EventBus and SpringEvent? I believe many inexperienced people don't know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Guava EventBus

The Guava EventBus implementation is the observer mode, which is easy to use and starts with code.

/ * * Desc: event object * / @ Data@NoArgsConstructor@AllArgsConstructorpublic class HelloEvent {private String eventName;} @ Data@NoArgsConstructorpublic class WorldEvent extends HelloEvent {private int eventNo; public WorldEvent (String name, int no) {setEventName (name); setEventNo (no);}} / * Desc: event listener, which can listen to multiple events. Just add the @ Subscribe annotation to the processing method. * / public class GeventListener {/ * listens for events of HelloEvent type and its parent type (Object) * / @ Subscribe public void processEvent (HelloEvent event) {System.out.println ("process hello event, name:" + event.getEventName ()) } / * listens for events of WorldEvent types and their parent types (HelloEvent and Object) * / @ Subscribe public void processWorldEvent (WorldEvent event) {System.out.println ("process world eventV1, no:" + event.getEventNo () + ", name:" + event.getEventName () } / * register multiple listeners to listen to the same event * @ param event * / @ Subscribe public void processWorldEventV2 (WorldEvent event) {System.out.println ("process world eventV2, no:" + event.getEventNo () + ", name:" + event.getEventName ());} @ Subscribe public void processObject (Object object) {System.out.println ("process common event, class:" + object.getClass (). GetSimpleName () }} public class GuavaTest {public static void main (String [] args) {EventBus eventBus = new EventBus (); GeventListener listener = new GeventListener (); eventBus.register (listener); eventBus.post (new HelloEvent ("hello")); eventBus.post (new WorldEvent ("world", 23333));}}

The results are as follows:

/ / HelloEvent is handled by two listeners (listeners of HelloEvent class and Object class) process hello event, name:helloprocess common event, class:HelloEvent//WorldEvent are handled by four listeners (two of their own and two parent classes) process world eventV1, no:23333, name:worldprocess world eventV2, no:23333, name:worldprocess hello event, name:worldprocess common event, class:WorldEvent

As can be seen from the above: Guava EventBus treats classes as events and registers and manages events with class for key. Value is an event listener whose method; event listener only handles a certain class (and its parent class) events.

Event registration and release

/ / com.google.common.eventbus.EventBus#register public void register (Object object) {/ / key is Class, value is EventSubscriber (Object target, Method method) [collection]. Note that Multimap is HashMultimap, that is, HashMap Multimap > dispatchTypes = flattenHierarchy (event.getClass ()); boolean dispatched = false; for (Class eventType: dispatchTypes) {subscribersByTypeLock.readLock (). Lock (); try {/ / find all event subscribers (event listeners) Set wrappers = subscribersByType.get (eventType); if (! wrappers.isEmpty ()) {dispatched = true; for (EventSubscriber wrapper: wrappers) {/ / event queue enqueueEvent (event, wrapper) } finally {subscribersByTypeLock.readLock (). Unlock ();} / / if no subscriber subscribes to such messages, DeadEvent if (! dispatched & &! (event instanceof DeadEvent)) {post (new DeadEvent (this, event));} dispatchQueuedEvents ();}

Event isolation

Multiple EventBus can isolate events.

Public class AnotherListener {/ * listens for events of WorldEvent types and their parent types (HelloEvent and Object) * / @ Subscribe public void processAnotherWorldEvent (WorldEvent event) {System.out.println ("process another world event, no:" + event.getEventNo () + ", name:" + event.getEventName ());}} public class GuavaTest {public static void main (String [] args) {EventBus eventBus = new EventBus (); GeventListener listener = new GeventListener (); eventBus.register (listener) EventBus.post (new HelloEvent ("hello")); EventBus anotherEventBus = new EventBus (); AnotherListener anotherListener = new AnotherListener (); anotherEventBus.register (anotherListener); anotherEventBus.post (new WorldEvent ("AnotherWorld", 666);}}

As a result,

/ / the eventBus result is the same as before. Events published by process hello event and name:hello//anotherEventBus are only handled by process common event, class:HelloEventprocess another world event, no:666, name:AnotherWorld by their registered listeners.

Applicable scenarios:

Event subscription event clusters are differentiated by class. Custom event is supported, and event isolation of dispensers can be written according to event.

Spring event

The event mechanism of the new version of spring is also relatively simple. Look at the code.

/ * events inherited from ApplicationEvent * / @ Datapublic class HelloEvent extends ApplicationEvent {private String eventName; public HelloEvent (String eventName) {super (eventName); setEventName (eventName);}} / * * Custom events * / @ Data@NoArgsConstructor@AllArgsConstructorpublic class CustomerEvent {private String name; private Boolean isCustomer } / * listener class, spring also supports listening to multiple events in one class * / @ Component ("springListener") public class SpringListener {/ * listening for events of all ApplicationEvent types and their subtypes * / @ EventListener public void processApplicationEvent (ApplicationEvent event) {System.out.println ("process common event, class:" + event.getClass (). GetSimpleName () } / * listen for HelloEvent type events * / @ EventListener public void processHelloEvent (HelloEvent event) {System.out.println ("process helloEvent, name:" + event.getEventName ());} / * listen for CustomerEvent type events, but the condition condition must be met, that is, isCustomer=true * / @ EventListener (condition = "# event.isCustomer") public void processCustomerEvent (CustomerEvent event) {System.out.println ("process customer CustomerEvent, name:" + event.getName ()) } / * listens for events of type CustomerEvent, but the condition condition must be met, that is, name= "miaomiao" * / @ EventListener (condition = "# event.getName (). Equals ('miaomiao')") public void processMiaoMiaoEvent (CustomerEvent event) {System.out.println ("process miaomiao's CustomerEvent, name:" + event.getName ()) } / * support asynchronous event handling * / @ Async @ EventListener public void processAsyncCustomerEvent (CustomerEvent event) {System.out.println ("Async process CustomerEvent, name:" + event.getName ());}} / / execution class, test entry @ SpringBootApplication@ComponentScan (basePackages = {"com.example.manyao.async"}) public class DemoApplication {public static void main (String [] args) throws TException {SpringApplication.run (DemoApplication.class, args); ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext.xml") String [] names = context.getBeanDefinitionNames (); for (int item0; I

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report