Spring Session usage

1. Usage scenarios

Without separating the front and back ends, store a user information in the session of the login page auth.gulimall.com . You want to retrieve the data and display it on the homepage gulimall.com .

 	@GetMapping("/oauth2.0/gitee/success")
    public String oauth2(@RequestParam("code") String code, HttpSession httpSession) throws Exception {
    
    
		......
		if (r.getCode() == 0){
    
    
                MemberOAuthVo memberOAuthVo = r.getData(new TypeReference<MemberOAuthVo>() {
    
    });
                log.info("用户信息:{}",memberOAuthVo);
                httpSession.setAttribute("loginUser",memberOAuthVo);
                return "redirect:http://gulimall.com";
	     }
	    ......
    }

front page
Insert image description here

2. Reasons why sessions are not shared

1. If you want to retrieve the session data, you need to use the JSESSIONID and Domain of the cookie . The Domain here stipulates which domain names the session can be used under. The Domain under each domain name is different, which means that the data of domain name a cannot be used by the domain name. bGet it

Insert image description here
Insert image description here

2. And the session is stored in the server memory. If there are multiple instances of a service, then the memory of each server cannot share the session.

3. Solution

1. Solve the problem that different domain names cannot share sessions

Enlarge the DOMAIN scope of JSESSIONID. It is impossible to manually modify the DOMAIN scope in actual combat. Use springsession to solve auth.gulimall.com -> .gulimall.com

2. Solve the problem that distributed services (different instances of the same service) do not share sessions

Store session in redis

4. Import Spring Session

1. Import dependencies (both stored and retrieved services need to be configured)

        <!--解决session不共享-->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>

2.application.properties

#session存储类型
spring.session.store-type=redis
#session过期时间: 默认30分钟
server.servlet.session.timeout=30

3. Add annotations to the startup class

Automatically store the data in HttpSession into redis. Originally, the HttpSession source code accessed and retrieved the session from the currentMap memory. Now, it retrieves the session from the wrapped wrappedRequest. It also operates to store and retrieve the session from redis.

@EnableRedisHttpSession

@EnableRedisHttpSession imports the RedisHttpSessionConfiguration configuration and adds a component
RedisOperationsSessionRepository to the container: Redis operation session, session addition, deletion, modification and encapsulation class

4. Custom configuration class

Solve the problem that the Domain subdomain name cannot obtain session data

@Configuration
public class GulimallSessionConfig {
    
    

    /**
     * 自定义session的使用范围——Domain
     */
    @Bean
    public CookieSerializer cookieSerializer(){
    
    
        DefaultCookieSerializer defaultCookieSerializer = new DefaultCookieSerializer();
        defaultCookieSerializer.setDomainName("gulimall.com");
        defaultCookieSerializer.setCookieName("GULISESSION");
        return defaultCookieSerializer;
    }

    /**  
     * 自定义redis序列化方式为json,原来是Serializable
     */
    @Bean
    public RedisSerializer<Object> redisSerializer(){
    
    
        return new GenericJackson2JsonRedisSerializer();
    }
}

5. Front-end value display

<li style="width: 100px;">
	<a th:if="${session.loginUser != null}">欢迎, [[${session.loginUser.username}]]</a>
	<a th:if="${session.loginUser == null}" href="http://auth.gulimall.com/login.html">你好,请登录</a>
</li>
<li>
	<a th:if="${session.loginUser == null}" href="http://auth.gulimall.com/reg.html" class="li_2">免费注册</a>
</li>

5. Achieve results

Click on the home page
Insert image description here
to log in—>Authorization successful—>Get user information—>User information is stored in session
Insert image description here

When the login page and the home page have different domain names, the login page authorizes the user information to be successfully stored in the session, jumps to the home page, and the home page takes out the user name in the session and displays it.
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_44847885/article/details/131366108