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

How to implement Spring event publishing and monitoring

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

Share

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

This article mainly explains the "Spring event release and monitoring how to achieve", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Spring event release and monitoring how to achieve" it!

I. introduction to the concepts related to event monitoring

1. Process analysis

Event: what has been done. For example, I am writing a blog, writing a blog is an event.

Listener: the component that listens to the event that occurs. For example, the fire alarm in our daily life monitors to see if there is a fire.

In a complete event system, there should be three concepts in addition to events and listeners.

1. Event source: the producer of the event. Any event must have an event source.

two。 Event broadcaster: it is a bridge between events and event listeners and is responsible for notifying event listeners

3. Event listener registry: the spring framework provides a place for all listeners to store

Through the flowchart, you can see how they perform their respective duties, as follows:

In fact, through the flowchart, we can easily find that the event system is the concrete realization of the observer pattern, and it does not have any mystery.

2. Process analysis

Structural analysis:

1. Event class (ApplicaitonEvent): currently, the spring framework itself provides only a few events, many of which need to be customized.

The only constructor for ApplicationEvent is ApplicaitonEvent (Object source), which specifies the event source through source. It has two subclasses.

(1) ApplicationContextEvent: container events, that is, the event source is ApplicationContext. The framework provides four subclasses that represent container start, refresh, stop and close events.

(2) RequestHandleEvent: this is an event related to the Web application, which occurs when a request is processed.

Generally speaking, we all extend ApplicationEvent to customize events. There will be chestnuts down there.

two。 Event listener interface (ApplicationListener)

All listeners need to implement this interface, which defines only one method: onApplicaitonEvent (E event), which receives the event object and writes the response handling logic for the event in this method.

II. Release and monitoring of handwritten simulation events

Note: for those who want to learn directly about Spring event monitoring and publishing, you can skip this section, but I suggest you take a look.

Demand:

Suppose the company now asks you to develop a file manipulation helper class

Define a file read-write method to read and write a file to a class / / but sometimes it may be necessary to record the need for a file to read the progress bar

Sometimes you need a progress bar. how to achieve it?

Answer: we can use event publishing and monitoring.

Event: file upload

Event source: where the event was published, for example, we published the event in Class A. Then the object of class An is the event source.

Listener: the FileUploadListener we wrote listens to this event. And after listening for the current event, publish the event.

Code writing:

/ * *

* @ ClassName ApplicationEvent

* @ Description

* @ Author EvanWang

* @ Version 1.0.0

* @ Date 20:29 on 2019-12-9

* /

Public class ApplicationEvent {

}

/ * *

* @ ClassName ApplicationListener

* @ Description

* @ Author EvanWang

* @ Version 1.0.0

* @ Date 20:29 on 2019-12-9

* /

Public interface ApplicationListener {

Void onEvent (E e)

}

/ * *

* @ ClassName ListenerManage

* @ Description

* @ Author EvanWang

* @ Version 1.0.0

* @ Date 20:44 on 2019-12-9

* /

/ / event Manager

Public class ListenerManage {

/ / Save all listeners

Static List > list = new ArrayList ()

/ / add listeners Note: if you want to do it more elegantly, you should scan the whole world, and put all listeners into the container list of the manager by scanning. Here, it will not be complicated to facilitate the demonstration.

/ / springboot obtains listener from the BeanFactory of spring

Public static void addListener (ApplicationListener listener) {

List.add (listener)

}

/ / determine which listeners are listening to this event

Public static void publishEvent (ApplicationEvent event) {

For (ApplicationListener applicationListener: list) {

/ / get the generics of ApplicationListener

Class typeParameter = (Class) ((ParameterizedType) applicationListener.getClass (). GetGenericInterfaces () [0]) .getActualTypeArguments () [0]

If (typeParameter.equals (event.getClass () {

ApplicationListener.onEvent (event)

}

}

}

}

/ * *

* @ ClassName FileUploadEvent

* @ Description

* @ Author EvanWang

* @ Version 1.0.0

* @ Date 21:37 on 2019-12-9

* /

Public class FileUploadEvent extends ApplicationEvent {

Private int fileSize

Private int readSize

Public FileUploadEvent (int fileSize, int readSize) {

This.fileSize = fileSize

This.readSize = readSize

}

Public int getFileSize () {

Return fileSize

}

Public void setFileSize (int fileSize) {

This.fileSize = fileSize

}

Public int getReadSize () {

Return readSize

}

Public void setReadSize (int readSize) {

This.readSize = readSize

}

}

/ * *

* @ ClassName FileUploadListener

* @ Description

* @ Author EvanWang

* @ Version 1.0.0

* @ Date 21:38 on 2019-12-9

* /

Public class FileUploadListener implements ApplicationListener {

@ Override

Public void onEvent (FileUploadEvent fileUploadEvent) {

Double molecule = fileUploadEvent.getFileSize ()

Double denominator = fileUploadEvent.getReadSize ()

System.out.println ("current file upload progress percentage:" + (denominator / molecule * 100 + "%"))

}

}

/ * *

* @ ClassName FileUtil

* @ Description

* @ Author EvanWang

* @ Version 1.0.0

* @ Date 17:06 on 2019-12-9

* /

Public class FileUtil {

Public static int READ_SIZE = 100

Public static void fileWrite (InputStream is, OutputStream os) throws Exception {

FileWrite (is, os, null)

}

Public static void fileWrite (InputStream is, OutputStream os, FileListener fileListener) throws Exception {

BufferedInputStream bis = new BufferedInputStream (is)

BufferedOutputStream bos = new BufferedOutputStream (os)

/ * *

* if it is a network request, it is best not to use this method to get fileSize, because this method will cause blocking. You'd better pass in a File object.

* here as a demonstration, we will not deal with the details.

* /

/ / Total file size

Int fileSize = is.available ()

/ / how many reads have been made?

Int readSize = 0

Byte [] readedBytes = new byte [read _ SIZE]

/ / controls whether to exit or not

Boolean exit = true

While (exit) {

/ / when the file is smaller than the size of the first read

If (fileSize < READ_SIZE) {

Byte [] fileBytes = new byte [fileSize]

/ / write the data in the buffer to the byte array fileBytes

Bis.read (fileBytes)

/ / write the contents of the fileBytes array to the file

Bos.write (fileBytes)

ReadSize = fileSize

Exit = false

/ / when you read it for the last time

} else if (fileSize < readSize + READ_SIZE) {

Byte [] bytes = new byte [fileSize-readSize]

ReadSize = fileSize

Bis.read (bytes)

Bos.write (bytes)

Exit = false

} else {

Bis.read (readedBytes)

ReadSize + = READ_SIZE

Bos.write (readedBytes)

}

/ / publish event

ListenerManage.publishEvent (new FileUploadEvent (fileSize, readSize))

If (fileListener! = null) {

FileListener.updateLoad (fileSize, readSize)

}

}

Bis.close ()

Bos.close ()

}

}

/ * *

* @ ClassName FileReadTest

* @ Description

* @ Author EvanWang

* @ Version 1.0.0

* @ Date 18:26 on 2019-12-9

* /

Public class FileReadTest {

Public static void main (String [] args) throws Exception {

ListenerManage.addListener (new FileUploadListener ())

/ / here, read and write files are set up according to the actual situation.

File file = new File ("F:\\ test write .txt")

If (! file.exists ()) {

File.createNewFile ()

}

/ / if you need to do the progress bar function, add another fileListener parameter

FileWrite (new FileInputStream (new File ("F:\\ what to do tomorrow .txt"), new FileOutputStream (file))

}

}

Running result:

Current file upload progress percentage: 14.2450142450142445%

Current file upload progress percentage: 28.49002849002849%

Current file upload progress percentage: 42.73504273504273%

Current file upload progress percentage: 56.98005698005698%

Current file upload progress percentage: 71.22507122507122%

Current file upload progress percentage: 85.470085470085546%

Current file upload progress percentage: 99.71509971509973%

Current file upload progress percentage: 100.0%

III. Time release and monitoring of Spring

We manually simulate the time of Spring publishing and monitoring above, and see if the above example, we use Spring to write another example of event publishing and monitoring. Http://rl.zyfuke.com/ of Zhengzhou abortion Hospital

Package com.evan.spring.config

Import org.springframework.context.annotation.ComponentScan

/ * *

* @ ClassName Appconfig

* @ Description

* @ Author EvanWang

* @ Version 1.0.0

* @ Date 16:04 on 2019-12-10

* /

@ ComponentScan ("com")

Public class AppConfig {

}

Package com.evan.spring.event

Import org.springframework.context.ApplicationContext

Import org.springframework.context.event.ApplicationContextEvent

Import org.springframework.context.event.ContextStartedEvent

/ * *

* @ ClassName MyEvent

* @ Description

* @ Author EvanWang

* @ Version 1.0.0

* @ Date 15:39 on 2019-12-10

* /

Public class WriteBlogEvent extends ApplicationContextEvent {

String name

String address

Public WriteBlogEvent (ApplicationContext source, String name, String address) {

Super (source)

This.name = name

This.address = address

}

Public String getName () {

Return name

}

Public String getAddress () {

Return address

}

}

Event listening for Spring can be based on annotations or implementation interfaces. For the same event, if both exist, it is equivalent to multiple listeners listening for an event.

Methods in both listeners are executed.

Package com.evan.spring.listener

Import com.evan.spring.event.WriteBlogEvent

Import org.springframework.context.ApplicationListener

Import org.springframework.stereotype.Component

/ * *

* @ ClassName WriteBlogListener

* @ Description

* @ Author EvanWang

* @ Version 1.0.0

* @ Date 15:47 on 2019-12-10

* /

@ Component

Public class WriteBlogListener implements ApplicationListener {

@ Override

Public void onApplicationEvent (WriteBlogEvent writeBlogEvent) {

String name = writeBlogEvent.getName ()

String address = writeBlogEvent.getAddress ()

System.out.println ("based on the implementation interface:" + name + "wrote a blog at" + address + ")

}

}

Package com.evan.spring.listener

Import com.evan.spring.event.WriteBlogEvent

Import org.springframework.context.event.EventListener

Import org.springframework.stereotype.Component

/ * *

* @ ClassName WriteBlogListenerAnnotation

* @ Description

* @ Author EvanWang

* @ Version 1.0.0

* @ Date 16:30 on 2019-12-10

* /

@ Component

Public class WriteBlogListenerAnnotation {

@ EventListener

Public void annotationListen (WriteBlogEvent writeBlogEvent) {

String name = writeBlogEvent.getName ()

String address = writeBlogEvent.getAddress ()

System.out.println ("based on comments:" + name + "wrote a blog at" + address + ")

}

}

Package com.evan.spring.test

Import com.evan.spring.config.AppConfig

Import com.evan.spring.event.WriteBlogEvent

Import org.springframework.context.annotation.AnnotationConfigApplicationContext

/ * *

* @ ClassName EventTest

* @ Description

* @ Author EvanWang

* @ Version 1.0.0

* @ Date 15:56 on 2019-12-10

* /

Public class EventTest {

Public static void main (String [] args) {

AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext (AppConfig.class)

WriteBlogEvent writeBlogEvent = new WriteBlogEvent (ac, "Evan", "home")

Ac.publishEvent (writeBlogEvent)

}

}

Running result:

Based on comments: Evan writes a blog at home

Based on the implementation interface: Evan wrote a blog at home

IV. Summary

1. How does spring know which listeners are available?

Through two steps: 1. Get all the Bean of ApplicationListener type from the Bean factory.

two。 Scan all with @ EventListener

2. How does spring publish events?

Logically, it goes through two steps: 1. Determine if any listeners are interested in the event

two。 Call the listener method

Thank you for your reading, the above is the content of "how to achieve Spring event release and monitoring". After the study of this article, I believe you have a deeper understanding of how to achieve Spring event release and monitoring, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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