In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
In the Spring environment of event-driven code example analysis, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
Although all kinds of applications are deployed in clusters, and fewer and fewer stand-alone applications are deployed, it is undeniable that there are still many stand-alone applications in the market. This article introduces the use of EventBus in Guava.
EventBus handles things similar to the observer pattern, based on event-driven, where observers listen for specific events of interest to them and deal with them accordingly.
Elegantly use EventBus in the Guava package in the Spring environment to decouple our code to a certain extent.
Step 0: add Guava to rely on com.google.guava guava 22.0 as a java programmer. If you haven't used Google Guava yet, please add it to every project from now on.
Step 1: define an annotation to mark listener / * *
Used to mark listener * / @ Target ({ElementType.TYPE}) @ Retention (RetentionPolicy.RUNTIME) public @ interface EventBusListener {} Step 2: define registry package com.javadoop.eventbus
Import java.util.List; import java.util.concurrent.Executors; import javax.annotation.PostConstruct; import org.springframework.stereotype.Component; import com.google.common.eventbus.AsyncEventBus; import com.google.common.eventbus.EventBus; import com.hongjiev.javadoop.util.SpringContextUtils
@ Component public class EventBusCenter {
/ / manage synchronous events private EventBus syncEventBus = new EventBus (); / / manage asynchronous events private AsyncEventBus asyncEventBus = new AsyncEventBus (Executors.newCachedThreadPool ()); public void postSync (Object event) {syncEventBus.post (event);} public void postAsync (Object event) {asyncEventBus.post (event);} @ PostConstructpublic void init () {/ / get all bean with @ EventBusListener and register them as listeners List listeners = SpringContextUtils.getBeansWithAnnotation (EventBusListener.class) For (Object listener: listeners) {asyncEventBus.register (listener); syncEventBus.register (listener);}}
} Step 3: define various events for example, let's define an order creation event:
Package com.javadoop.eventbus.event
Public class OrderCreatedEvent {private long orderId; private long userId; public OrderCreatedEvent (long orderId, long userId) {this.setOrderId (orderId); this.setUserId (userId);} / getter, setter} Step 4: define event listeners. First of all, the class needs to be annotated with @ EventBusListener, and then the listener method needs to be annotated @ Subscribe, and the method parameters are specific events.
Package com.javadoop.eventbus.listener
Import org.springframework.stereotype.Component; import com.google.common.eventbus.Subscribe; import com.javadoop.eventbus.EventBusListener; import com.javadoop.eventbus.event.OrderCreatedEvent
@ Component @ EventBusListener public class OrderChangeListener {
@ Subscribepublic void created (OrderCreatedEvent event) {long orderId = event.getOrderId (); long userId = event.getUserId (); / / various actions after the order is successfully created, such as SMS, email, and so on. / / Note that events can be subscribed multiple times, that is, there are many ways to listen to OrderCreatedEvent events. / / so there is no need to deal with texting, emailing, updating inventory, etc. @ Subscribepublic void change (OrderChangeEvent event) {/ / handle changes after order changes / / such as sending reminders, updating logistics, etc.}
} Step 5: send event @ Service public class OrderService {
@ Autowiredprivate EventBusCenter eventBusCenter;public void createOrder () {/ / process order creation / /... / / send asynchronous event eventBusCenter.postAsync (new OrderCreatedEvent (1L, 1L));}
The advantage of summarizing EventBus is that it decouples the code that occurs the event from the code that handles it.
For example, orders can be modified in many places in the system, and users can modify them themselves, customer service can also modify them, or even order modifications that are not carried out by the group buying system. All these places that trigger order changes have to send text messages and e-mails. Assuming that other operations will be added in the future, there are more places that need to be modified.
If you use event-driven, as long as events are thrown in these places, subsequent maintenance is relatively simple.
Moreover, EventBus supports synchronous and asynchronous events, which can meet our needs in different scenarios. For example, sending text messages, there is no need for the system to wait there, it can be done asynchronously.
Appendix: the code above SpringContextUtils uses SpringContextUtils. I think most Spring applications will write a utility class to get Bean from the Spring container for places where it is not convenient to adopt injection.
@ Component public class SpringContextUtils implements BeanFactoryPostProcessor {
Private static ConfigurableListableBeanFactory beanFactory;@Overridepublic void postProcessBeanFactory (ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {SpringContextUtils.beanFactory = configurableListableBeanFactory;} public static T getBean (String name) throws BeansException {return (T) beanFactory.getBean (name);} public static T getBean (Class clz) throws BeansException {T result = beanFactory.getBean (clz); return result;} public static List getBeansOfType (Class type) {return beanFactory.getBeansOfType (type). EntrySet (). Stream (). Map (entry- > entry.getValue ()). } / / the above example uses this public static List getBeansWithAnnotation (Class)
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.