The problem solved by applying eventbus in the project
In the process of project development, some functions often look simple on the surface, but the actual development results are very complex. The reason for careful analysis is that many of them are due to the addition of many additional features.
Is it really simple?
For example, the function of modifying the product data on an e-commerce platform is actually very simple. It is nothing more than the Operation staff modifying the product data on the management platform, and then click Submit, the core function is indeed very simple, but some people may require that operation logs be added to all changes to the product. Some people also propose to automatically update the data in the retrieval system after the product data is modified, someone needs to review the item data before the modification can take effect, and someone needs to send an email to the operator to notify them. As a result, the function of modifying the item is not that simple, in addition to fulfilling its mission, it also needs to call other services to complete the process. The activities are similar to the following:
For a horizontal main flow, the four small boxes above and below are additional functions. The complex reasons include the following:
- Additional features lead to more feature activation and increased workload
- Additional functions make the program logic complex. You need to access other services in the program. You also need to consider data integrity, performance, service dependencies, and other issues.
At the beginning of our project development, we used the simplest strong coupling to directly call the service. For example, after calling the data storage method, call the log method of logService to record logs, call the esService method to update the retrieval system, and call the mailService method to send emails, this will cause our productService to be strongly coupled with these services that are not directly related to the product storage logic. This makes it seem that the product storage function is not so simple, that is, the premise of our article is complicated, similar code will appear:
@ Autowiredprivate SearchService searchService; @ Autowiredprivate MailService mailService; @ Autowiredprivate ProductLogService productLogService; // The code snippet itemDao for saving the product is as follows. save (product); searchService. update (product. getId (); mailService. post (product. getId (); logService. log (product. getId ());
The problem is as follows:
- Strong Coupling with services without direct business association
- There may be performance problems. For example, you need to check whether email sending will affect the main process.
- The code is less readable, and excessive logic may lead to unclear core functions of the subject.
What if the problem is solved? There is a design pattern that can be solved, that is, the observer pattern, which was learned before. net has written a special article (conventional: Observer mode), which mentions the traditional implementation methods and the event mechanism. The implementation of the event mechanism is relatively simple, the eventbus provided by the guava component is referenced in solving this problem. It is similar to the implementation of the observer mode in the previous article. See the figure below, there is no intricate dependency between functions.
Note: The eventbus of guava is in-process level and cannot be cross-process. I will take the time to sort out the message queue-based Distributed Event summary.
Here I will not introduce how to use EventBus, but will focus on the application of EventBus in our project and what is not doing well.
First, we need to have an observer. Here we encapsulate different observers based on different businesses. The following is a class for updating and retrieving system data.
@ Service public class SearchEventListener {@ Autowired () ProductUpdateMgr productSearchUpdateMgr; private final static Logger logger = LoggerFactory. getLogger (SearchEventListener. class); @ Subscribe public void listen (String itemLegacyId) {try {productSearchUpdateMgr. markProductDirty (itemLegacyId);} catch (Exception ex) {logger. error ("Update retrieval exception:" + ex. getMessage () + ex. getStackTrace ());}}}
Second, we need to register the observer to eventbus. We specifically write a class to do this and complete two things:
- Register the observer to eventbus
- The post method is further packaged so that the caller can call the method as a service, so that productService depends on eventbus instead of the actual retrieval service or email service.
@Servicepublic class EventListenerManager { EventBus mmsProductEventBus; EventBus mmsItemEventBus; EventBus mmsSearchEventBus; EventBus mmsRebuildAllSearchEventBus; EventBus mmsCommonLogEventBus; @Autowired ItemEventListener itemListener; @Autowired ProductEventListener productListener; @Autowired SearchEventListener searchListener; @Autowired RebuildAllSearchEventListener rebuildAllSearchListener; @Autowired MmsCommonLogEventListener commonLogListener; @PostConstruct private void init() { mmsProductEventBus = new EventBus(); mmsItemEventBus = new EventBus(); mmsSearchEventBus = new EventBus(); mmsRebuildAllSearchEventBus=new EventBus(); mmsCommonLogEventBus=new EventBus(); mmsItemEventBus.register(itemListener); mmsProductEventBus.register(productListener); mmsSearchEventBus.register(searchListener); mmsRebuildAllSearchEventBus.register(rebuildAllSearchListener); mmsCommonLogEventBus.register(commonLogListener); } public void notifyItemLog(Long itemId) { mmsItemEventBus.post(itemId); } public void notifyProductLog(Long productId) { mmsProductEventBus.post(productId); } public void notifyUpdateSearch(String itemLegacyId) { mmsSearchEventBus.post(itemLegacyId); } public void notifyRebuildAllSearch() { mmsRebuildAllSearchEventBus.post(""); } public void notifyAddCommonLog(MmsCommonLogModel log) { mmsCommonLogEventBus.post(log); }}
What problems did we encounter when we first learned how to use guava eventbugs?
Question 1:Why does the above Code have so many eventbus instead of one? Note the post method of enventbus. Let's look at its source code: It comes to the observer registration method based on the parameter type, the parameters in the methods in the Observer class we write are of the primitive type. There are about 10 methods in total. to correctly identify which method to call in an eventbus Based on the parameter type, it is relatively difficult.
public void post(Object event) { Set<Class<?>> dispatchTypes = flattenHierarchy(event.getClass()); boolean dispatched = false; for (Class<?> eventType : dispatchTypes) { subscribersByTypeLock.readLock().lock(); try { Set<EventSubscriber> wrappers = subscribersByType.get(eventType); if (!wrappers.isEmpty()) { dispatched = true; for (EventSubscriber wrapper : wrappers) { enqueueEvent(event, wrapper); } } } finally { subscribersByTypeLock.readLock().unlock(); } } if (!dispatched && !(event instanceof DeadEvent)) { post(new DeadEvent(this, event)); } dispatchQueuedEvents(); }
How can this problem be solved?A class can be encapsulated for the parameters of each method. For example, the parameter of the updated retrieval method is SearchChangeEvent, and the parameter of the sent audit email is ApprovalChangeEvent, in this way, we can register all the observers to an eventbus, so that no problem will occur when the post method is called. The simplified result is as follows:
@ AutowiredEventListenerManager eventManager; // Save the itemDao code snippet of the product as follows. save (product); eventManager. post (new SearchChangeEvent (product. getId); eventManager. post (new MailChangeEvent (product. getId); eventManager. post (new LogChangeEvent (product. getId ));
Question 2:Performance problems. I have mentioned that additional functions may lead to simple things. For example, calling some services may affect the overall performance, at that time, we thought that the enventbus itself was asynchronous. In fact, if eventbus is used for synchronization, we need to use this class to complete AsyncEventBus.
Question 3:Due to the strong coupling problem, with EventListenerManager, we do not need to rely on non-directly related services in specific services, you only need to rely on EventListenerManager, a management class that seems unrelated to the task business.
Analyze the problems it can solve through the eventbus application in the actual project and the areas where the original application needs to be improved. It is obvious that the proper eventbus application can simplify Program Complexity, improve code readability, and reduce development and maintenance costs.