Create a MAvNE project using srping, which we use with spring-Session.

Add the dependent

<! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <! --redis-session--> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>Copy the code

The configuration file

Host = # port= # password= # spring.redis. Password = # library = spring.redisCopy the code

Enable the Redis Http session

@Configuration
@EnableRedisHttpSession
public class RedisSessionManager {
}
Copy the code

At this point, the project has implemented the Redis management Session.

Using the analysis

Let’s examine a piece of code:

@RequestMapping() public void test(HttpServletRequest request, HttpServletResponse Response throws IOException {HttpSession session = request.getSession(); List<String> list = (List<String>) session.getAttribute("list"); if (list == null){ list = new ArrayList<>(); // add redis session.setAttribute("list",list); } list.add("y2m"); response.getWriter().println("size:"+list.size()); response.getWriter().println("sessionId:"+session.getId()); }Copy the code

The first time you access the file, the second time you access the file, the third time you access the file, the second time you access the file, the third time you access the file, the second time you access the file, the third time you access the file, the third time you access the file

Interpretation of results:

When you first access redis, there is no session. The session is the server’s session object and the Java object. Size: 1 is output naturally

So when you go to redis for the second time and you have a session, you get the session from Redis and the list size is 1 and you add it and the size is 2 and you don’t update the new list to the list of Redis, So the size of redis’ list is still 1

In the future are such…………

Thinking: why not apply redis session management and the following code will work? The address of the list in the heap does not change because JVMS manage sessions in the heap

Code optimization

/** * Add redis whenever session changes. * @param Request * @param Response * @throws IOException */ @requestMapping () public void optimization(HttpServletRequest request, HttpServletResponse Response throws IOException {HttpSession session = request.getSession(); List<String> list = (List<String>) session.getAttribute("list"); if (list == null){ list = new ArrayList<>(); // add redis session.setAttribute("list",list); } list.add("y2m"); // add redis to synchronize session.setAttribute("list",list); response.getWriter().println("size:"+list.size()); response.getWriter().println("sessionId:"+session.getId()); }Copy the code
// Remove request.getSession().invalidate();Copy the code