Based on SpringSession combined with redis for session sharing and monitoring

生命无罪,健康万岁,我是laity。

Seven times have I despised my soul:

For the first time, it feigned humility when it could have been aggressive;

The second time, when it was empty, fill it with lust;

The third time, between difficult and easy, it chose easy;

For the fourth time, it made a mistake, but comforted itself by saying that others would also make mistakes;

The fifth time, it is free and weak, but it is regarded as the tenacity of life;

The sixth time, when it despises an ugly face, it does not know that it is one of its own masks;

For the seventh time, it leaned sideways in the mud of life, although it was not reconciled, it was timid.

SpringSession

It is used to solve the problem of non-sharing and non-synchronization of Session under distributed

core principle

insert image description here
Core Code Analysis
insert image description here
Conclusion: Wrapper Mode (Decorator Mode)
insert image description here

/**
 * SpringSession核心原理
 *  1、@EnableRedisHttpSession 导入了 @Import({RedisHttpSessionConfiguration.class})
 *    1)、给容器中添加了一个组件
 *      RedisIndexedSessionRepository:redis操作session,session的增删改查的封装类
 *    2)、SessionRepositoryFilter:session存储过滤器  ==> Filter:每个请求都经过过滤器
 *      创建的时候,就自动从容器中获取到了SessionRepository;
 *      原始的request、response都被包装
 *      从原始的 request.getSession() => wrappedRequest.getSession(); => private final SessionRepository<S> sessionRepository; 中获取
 *      private final SessionRepository<S> sessionRepository;  | redis、jdbc、mangodb
 *      所以只是用了包装模式(装饰者模式)
 *      并且 springSession会自动延期session时间,浏览器一关就删除session
 */

SpringBoot integrates SpringSession

  • import dependencies
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
            <version>2.3.0.RELEASE</version>  <!--这个版本是我Springboot版本-->
        </dependency>
  • application.yml
server:
  servlet:
    session:
      timeout: 30m  # session的过期时间
spring:
  redis:   # Redis配置
    port: 你本人Redis端口
    host: 你本人Redis服务地址
    password: 你本人Redis服务密码(有则写)
  session: # 指定session处理的store-type(就是存储位置)
    store-type: redis
  • Open Spring Session

@EnableRedisHttpSession

@EnableRedisHttpSession  // SpringSession解决session共享问题:整合redis做为我们session的存储
@EnableDiscoveryClient
@EnableAsync
@ServletComponentScan
@EnableFeignClients(basePackages = {
    
    "com.laity.auth.feign"})
@SpringBootApplication
public class AuthServerApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(AuthServerApplication.class, args);
    }
    
}
  • Business code

Session sharing is applied to the login interface: account password login and social login (qq, WeChat, etc.)

    @GetMapping(value = {
    
    "/gitee/success", "/github/success"})
    @ApiOperation(value = "获取gitee授权码", notes = "access_token获取用户信息")
    public String git(@RequestParam("code") String code, HttpSession session) throws Exception {
    
    
    		// ......此处省略与案例不相关代码
            session.setAttribute("你的key", "你的数据");
            // 这里如果要往Redis中存入内存对象,那么一定不要忘记将你要存入的对象进行序列化操作
            // ......此处省略与案例不相关代码
    }
  • Session sharing

Distributed session token cookies can only be assigned to the current domain name, and other domain names cannot share the session, so the scope of the session token should be expanded to solve the problem of session subdomain sharing

@Configuration
public class MySessionConfig {
    
    

    /*默认发的令牌。当前域(解决子域session共享问题)*/
    @Bean
    public CookieSerializer cookieSerializer() {
    
    
        DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();
        //放大作用域
        cookieSerializer.setDomainName(".laity.com");  // 我这里直接domain的作用域扩大到主域名下
        cookieSerializer.setCookieName("SESSION"); // 自定义令牌名
        return cookieSerializer;
    }

    /*使用JSON的序列化方式来序列化对象到Redis中 - 序列化机制*/
    @Bean
    public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
    
    
        return new GenericJackson2JsonRedisSerializer();
    }
    
}

problems encountered

Error 1 and solved

setting spring.main.allow-bean-definition-overriding=true

This configuration is generally written under application.properties of springboot

This configuration is mainly to declare whether the spring framework allows the bean object with the same name to overwrite the original bean (spring boot defaults to false)

spring.main.allow-bean-definition-overriding = true is to allow the definition of the same bean object to overwrite the original
spring.main.allow-bean-definition-overriding = false is not allowed to define the bean object of the same name

Here is just to emphasize the role of setting spring.main.allow-bean-definition-overriding=true The reason why
I reported this error is because I wrote @EnableRedisHttpSession wrong

Error 2 and solved

Cannot serialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is java.lang.IllegalArgumentException:

Store the memory object in redis - so the object must be serialized into stream or binary data first, and the corresponding class needs to implement the Serializable interface
implements Serializable

@Data
public class UserResponseBO implements Serializable {
    
    
	private String name;
	private Integer gender;
}

True proficiency requires continuous exploration by yourself, thank you for watching~

Guess you like

Origin blog.csdn.net/duyun0/article/details/127484385