In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, the editor will share with you the relevant knowledge about how to use the listener in SpringBoot. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
1. Listener
Web listeners are special classes in Servlet that help developers listen to specific events in web, such as the creation and destruction of ServletContext,HttpSession,ServletRequest, the creation, destruction, and modification of variables. You can add processing before and after some actions to achieve monitoring.
The use of listeners in 2.SpringBoot
There are many scenarios in which web listeners are used, such as listening to servlet context to initialize some data, listening to http session to obtain the number of people currently online, listening to servletrequest objects requested by clients to obtain user access information, and so on.
2.1 listening for Servlet context objects
Listening Servlet context objects can be used to initialize data for caching. For example, when a user clicks on the home page of a website, it usually shows some information on the home page, and the information remains basically or most of the time unchanged, but the information comes from the database. If users have to get data from the database every time they click, the number of users is acceptable, if the number of users is very large. This is also a big expense for the database.
For this kind of home page data, if most of the data are not updated frequently, we can cache them. Every time a user clicks, we take them directly from the cache, which can not only improve the access speed of the home page, but also reduce the pressure on the server. If we do it more flexibly, we can add a timer to update the home page cache regularly. It is similar to the change in the ranking on the home page of csdn personal blog.
Let's write a Service for this function to simulate querying data from a database:
Package com.example.springdemo1.service;import com.example.springdemo1.pojo.User;import org.springframework.stereotype.Service;@Servicepublic class UserService2 {public User getUser () {/ / actually query the corresponding information return new User (10, "lyh20", "123456") from the database according to the specific business scenario;}}
Then write a listener, implement the ApplicationListener interface, override the onApplicationEvent method, and pass the ContextRefreshedEvent object in. If we want to refresh our preloaded resources when loading or refreshing the application context, we can do this by listening to ContextRefreshedEvent, as follows:
Package com.example.springdemo1.util;import com.example.springdemo1.pojo.User;import com.example.springdemo1.service.UserService2;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationListener;import org.springframework.context.event.ContextRefreshedEvent;import org.springframework.stereotype.Component;import javax.servlet.ServletContext;@Componentpublic class MyServletContextListener implements ApplicationListener {@ Override public void onApplicationEvent (ContextRefreshedEvent contextRefreshedEvent) {/ / get the application context ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext () / / get the corresponding Service UserService2 userService2 = applicationContext.getBean (UserService2.class); User user = userService2.getUser (); / / get the application domain object, and put the information found in the application domain ServletContext application = applicationContext.getBean (ServletContext.class); application.setAttribute ("user", user);}}
First, get the application context through contextRefreshedEvent, then get the bean of UserService through the application context, then call your own business code to get the corresponding data, and finally store it in the application field, so that when the front end requests the corresponding data, we can get the information directly from the application field to reduce the pressure on the database. Here is a controller to get the user information directly from the application field to test it.
Package com.example.springdemo1.controller;import com.example.springdemo1.pojo.User;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.servlet.ServletContext;import javax.servlet.http.HttpServletRequest;@RestController@RequestMapping ("/ testListener") public class testController12 {@ GetMapping ("/ user") public User getUser (HttpServletRequest request) {ServletContext application = request.getServletContext () Return (User) application.getAttribute ("user");}}
To start the project, type http://localhost:8082/testListener/user in the browser for testing. If the user information is returned normally, the data has been cached successfully. However, such things as application are cached in memory and will consume memory.
2.2 listening for HTTP session Session objects
Another common place for listeners is to listen on session objects to get the number of online users.
Package com.example.springdemo1.util;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import javax.servlet.http.HttpSessionEvent;import javax.servlet.http.HttpSessionListener;@Componentpublic class MyHttpSessionListener implements HttpSessionListener {private static Logger logger = LoggerFactory.getLogger (MyHttpSessionListener.class); / / record the number of users online public Integer count = 0; @ Override public synchronized void sessionCreated (HttpSessionEvent httpSessionEvent) {logger.info ("new users are online"); count++ HttpSessionEvent.getSession () .getServletContext () .setAttribute ("count", count);} @ Override public synchronized void sessionDestroyed (HttpSessionEvent httpSessionEvent) {logger.info ("user offline"); count--; httpSessionEvent.getSession () .getServletContext () .setAttribute ("count", count);}}
As you can see, first the listener needs to implement the HttpSessionListener interface, then override the sessionCreated and sessionDestroyed methods, pass a httpSessionEvent object in the sessionCreated method, and then add one to the number of users in the current session. The sessionDestroyed method is just the opposite, so we won't repeat it, and then we'll write a controller to test it:
Package com.example.springdemo1.controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest @ RestController@RequestMapping ("/ testMyListener") public class testController13 {/ * get the current number of online users. The method is bug * @ param request * @ return * / @ GetMapping ("/ total") public String getTotalUser (HttpServletRequest request) {Integer count = (Integer) request.getSession (). GetServletContext (). GetAttribute ("count"); return "current online number:" + count }} these are all the contents of the article "how to use listeners in SpringBoot". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
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.