


Learn Spring Session and Redis to solve distributed Session cross-domain sharing issues
Use Spring Session and Redis to solve the problem of distributed Session cross-domain sharing
Explanation of the phenomenon:
The front-end and back-end codes in the project are not After separation, when the service is running normally on two instances, a prompt similar to the need to log in again will pop up occasionally, and the background error message
is a processor exception. The reason is not obvious.
After adding a machine instance, when accessing the front-end page, the login page is repeatedly accessed, resulting in page 302. Various signs indicate that it is caused by login configuration issues.
Related topic recommendations: php session (including pictures, texts, videos, cases)
Problem introduction : Session cannot be shared, resulting in polling between different machines requiring login, resulting in final service exception
Solution: Use Spring Session and Redis to solve the problem of distributed Session cross-domain sharing
Solution to configuration:
1 )Add dependency
<dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> <version>1.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency>
2 )Add web.xml configuration file:
<!-- 分布式Session共享Filter --> <filter> <filter-name>springSessionRepositoryFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSessionRepositoryFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
3) Spring.xml configuration
<!-- 将session放入redis --> <context:annotation-config/> <bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"> <property name="maxInactiveIntervalInSeconds" value="120" /> </bean> <bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <!-- redis 配置 --> <property name="hostName" value="192.168.0.48" /> <property name="port" value="6379" /> </bean>
Analysis:
1. DelegatingFilterProxy class in web: It belongs to the proxy fiter, which will start loading after tomcat starts. When filtering in web.xml, the management of the filter is handed over to the beans in spring. That is, the third step of the configuration introduces RedisHttpSessionConfiguration
2. RedisHttpSessionConfiguration inherits the SpringHttpSessionConfiguration class. This class is very important. SpringHttpSessionConfiguration passes @Bean Inject springSessionRepositoryFilter into the container
SessionRepositoryFilterThis filter is the filter searched for by DelegatingFilterProxy. The SessionRepositoryFilter is the key. How is it related?
springSessionRepositoryFilterThis filter
SessionRepositoryFilter is to replace the container's default javax.servlet.http.HttpSession support to
org.springframework.session.Session. The main methods and properties of
##5. Among them,
, SessionRepositoryRequestWrapper
, HttpSessionWrapper
is an internal class, which is also very critical. For example, the SessionRepositoryRequestWrapper class
It can be seen that the SessionRepositoryRequestWrapper inherits the javax.servlet.http.HttpServletRequestWrapper class. We know that the default implementation of the HttpServletRequest interface is HttpServletRequestWrapper, as follows
6. Because SessionRepositoryRequestWrapper inherits HttpServletRequestWrapper, and HttpServletRequestWrapper implements the HttpServletRequest interface. In SessionRepositoryRequestWrapper, it rewrites some methods in the HttpServletRequest interface, so there are: getSession, changeSessionId, etc. method. At this point, we should roughly understand that the original request and response have been repackaged. We also understand how the original HttpSeesion was replaced by Spring Session.
We use the shortcut keys to view the specific implementation of request.getSession(), and we can see that there is already a method overridden by SessionRepositoryRequestWrapper. There are two default implementations above, one is original and the other is implemented by Spring Session. Which one should be selected as the implementation? This is the role of the DelegatingFilterProxy proxy we mentioned above. It will filter each request through DelegatingFilterProxy Each request will also go through the springSessionRepositoryFilter filter. The springSessionRepositoryFilter filter realizes the conversion of the original request to the SessionRepositoryRequestWrapper. This is the specific process!
request.getSession().setAttribute(name, value)
Implementation: Tracking the code, you can reach the content below
You can see that there are Redis related operate! At this point, we should know how Spring Session works! Although the process below is not introduced again, it is already clearly understood.
Related learning recommendations: redis video tutorial
The above is the detailed content of Learn Spring Session and Redis to solve distributed Session cross-domain sharing issues. For more information, please follow other related articles on the PHP Chinese website!

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

Redis is a NoSQL database suitable for efficient storage and access of large-scale data. 1.Redis is an open source memory data structure storage system that supports multiple data structures. 2. It provides extremely fast read and write speeds, suitable for caching, session management, etc. 3.Redis supports persistence and ensures data security through RDB and AOF. 4. Usage examples include basic key-value pair operations and advanced collection deduplication functions. 5. Common errors include connection problems, data type mismatch and memory overflow, so you need to pay attention to debugging. 6. Performance optimization suggestions include selecting the appropriate data structure and setting up memory elimination strategies.

The applications of Redis in the real world include: 1. As a cache system, accelerate database query, 2. To store the session data of web applications, 3. To implement real-time rankings, 4. To simplify message delivery as a message queue. Redis's versatility and high performance make it shine in these scenarios.

Redis stands out because of its high speed, versatility and rich data structure. 1) Redis supports data structures such as strings, lists, collections, hashs and ordered collections. 2) It stores data through memory and supports RDB and AOF persistence. 3) Starting from Redis 6.0, multi-threaded I/O operations have been introduced, which has improved performance in high concurrency scenarios.

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools