In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "Redis how to quickly achieve distributed session", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "Redis how to quickly achieve distributed session" this article.
Preface
We usually need login authentication when developing a project. The common implementation frameworks of login authentication are Spring Security and shiro.
Spring Security
Spring Security is a powerful and highly customizable authentication and access control framework. It is the de facto standard for protecting spring-based applications.
Spring Security is a framework that focuses on providing authentication and authorization for Java applications. Like all Spring projects, the real power of Spring Security is that it can be easily extended to meet custom needs, and that Spring Security and spring are more adaptable, and we often use Spring Security in our work.
Apache Shiro
Apache Shiro is a security framework of Java. At present, more and more people are using Apache Shiro, because it is quite simple, and it may not be as powerful as Spring Security compared to Spring Security, but it may not require so complex things in actual work, so using a small and simple Shiro is sufficient.
Deficiency:
These are authentication technical frameworks, which are commonly used in single applications, but in distributed applications, multiple applications may have to deploy multiple copies, and requests may be distributed through nginx, but each single application may be verified repeatedly because their seesion data is placed in their own services.
Session action
Session is the communication session tracking technology between the client and the server. The server and the client keep the basic information of the whole communication session.
When the client accesses the server for the first time, the server responds to a sessionId and stores it in the local cookie, and later access puts the sessionId in the cookie into the request header to access the server.
Spring-session
Spring Session is one of Spring's projects. Spring Session replaces httpSession implemented by the servlet container with spring-session, focusing on solving session management problems.
Spring Session provides cluster Session (Clustered Sessions) function, which uses external Redis to store Session data by default, so as to solve the problem of Session sharing.
Spring-session provides a series of api and implementations for user session management. Many scalable and transparent encapsulation methods are provided to manage the processing of httpSession/WebSocket.
Support function
It is easy to store session in third-party storage containers, and the framework provides a variety of ways to store session containers, such as redis, jvm's map, mongo, gemfire, hazelcast, jdbc, and so on. This provides a high-quality cluster independent of the application server.
The same browser, the same website, supports multiple session problems. This makes it easy to build a richer end-user experience.
Restful API, not dependent on cookie. JessionID can be passed through header. Controlling how session id exchanges between the client and server makes it easy to write Restful API because it can get session id from the HTTP header information instead of relying on cookie
WebSocket and spring-session are combined to synchronize lifecycle management. When a user sends a request using WebSocket
Distributed seesion practice step 1: dependency package
Because it's a web app. We add the common dependency package web of springboot, the dependency package of SpringSession and redis, and move the support for storing session in redis
Org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.projectlombok lombok 1.18.8 org.springframework.boot spring-boot-starter-redis 1.4.7.RELEASE org.springframework.session spring-session-data-redis
Here because the seesion is stored in the redis, so that each service login is to view the data in the redis for authentication, all distributed. Spring-session-data-redis and spring-boot-starter-redis will be introduced here.
Step 2: the configuration file spring.application.name=spring-boot-redisserver.port=9090# sets how session is stored Use redis to store spring.session.store-type=redis# session valid duration for 15 minutes server.servlet.session.timeout=PT15M## Redis configuration # # Redis database index spring.redis.database=1## Redis server address spring.redis.host=127.0.0.1## Redis server connection port spring.redis.port=6379## Redis server connection password (default is empty) spring.redis.password= step 3: implement logic
Initialize user data
@ Slf4j@RestController@RequestMapping (value = "/ user") public class UserController {Map userMap = new HashMap (); public UserController () {/ / initialize a user to simulate login to User u1=new User (1, "user1", "user1"); userMap.put ("user1", U1);}}
Instead of using the database here, initialize two pieces of data instead of the database for simulated login
Log in
@ GetMapping (value = "/ login") public String login (String username, String password, HttpSession session) {/ / simulated database lookup User user = this.userMap.get (username); if (user! = null) {if (! password.equals (user.getPassword () {return "wrong username or password!!" ;} else {session.setAttribute (session.getId (), user); log.info ("login succeeded {}", user);}} else {return "wrong username or password!!" ;} return "login succeeded!!" ;}
Login API, log in according to the user name and password, and verify here. If the verification login is successful, use session.setAttribute (session.getId (), user); put the relevant information in the session.
Find users
/ * * find the user by user name * / @ GetMapping (value = "/ find/ {username}") public User find (@ PathVariable String username) {User user=this.userMap.get (username); log.info ("find the user {} by user name = {}", username,user); return user;}
Simulate finding a user through a user name
Get session
/ * take current user's session * / @ GetMapping (value = "/ session") public String session (HttpSession session) {log.info ("current user's session= {}", session.getId ()); return session.getId ();}
Log out
/ * exit login * / @ GetMapping (value = "/ logout") public String logout (HttpSession session) {log.info ("exit login session= {}", session.getId ()); session.removeAttribute (session.getId ()); return "exit successfully!!" ;}
When you exit here, delete the user information in session.
Step 4: write the session interceptor
The function of session interceptor: verify whether the request sent by the current user carries sessionid, and if not, prompt the user to log in again.
Configuration public class SecurityInterceptor implements HandlerInterceptor {@ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {HttpSession session = request.getSession () / / verify whether the current session exists. If there is a returned true true, it indicates that the business logic if (session.getAttribute (session.getId ())! = null) {log.info ("session interceptor, session= {}, passed", session.getId ()); return true } / / session does not exist, return false and prompt to log in again. Response.setCharacterEncoding ("UTF-8"); response.setContentType ("application/json; charset=utf-8"); response.getWriter () .write ("Please login!") ; log.info ("session interceptor, session= {}, validation failed", session.getId ()); return false Step 5: inject the interceptor into the interceptor chain @ Slf4j@Configurationpublic class SessionCofig implements WebMvcConfigurer {@ Override public void addInterceptors (InterceptorRegistry registry) {registry.addInterceptor (new SecurityInterceptor ()) / / exclude 2 intercepted paths.intercepdePathPatterns ("/ user/login") .intercepdePathPatterns ("/ user/logout") / / intercept all URL paths .addPathPatterns ("/ *") Step 6: test
Log in to user1 user: http://127.0.0.1:9090/user/login?username=user1&password=user1
Query user1 user session: http://127.0.0.1:9090/user/session
Log out and login: http://127.0.0.1:9090/user/logout
View the data in redis after logging in:
The seesion data has been saved to redis, so here we have integrated the distributed seesion function using spring-seesion.
These are all the contents of the article "how to quickly implement distributed session in Redis". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow 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.