SpringBoot+Redis实现session共享和SpringMvc+redis实现session共享

SpringBoot+Redis实现session共享

1、引入jar包依赖


   redis.clients
   jedis
   2.9.0



   org.springframework.session
   spring-session-data-redis

2、添加配置

/**
 * EnableCaching 开启redis缓存
 * EnableRedisHttpSession 配置session共享,设置Session失效时间为60分钟
 */
@Configuration
@EnableCaching
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600)
public class RedisUtil {
    @Autowired
    private static JedisPool jedisPool;

    @Bean(name= "redis.util")
    @Autowired
    public static JedisPool jedisPool(@Value("${spring.redis.host}") String host,
                                      @Value("${spring.redis.port}")int port,
                                      @Value("${spring.redis.password}") String password,
                                      @Value("${spring.redis.timeout}")int timeout,
                                      @Value("${spring.redis.pool.max-active}")int maxActive,
                                      @Value("${spring.redis.pool.max-idle}")int maxIdle,
                                      @Value("${spring.redis.pool.max-wait}")int maxWaitMillis,
                                      @Value("${spring.redis.pool.test-on-borrow}")boolean testOnBorrow) {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxActive);
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWaitMillis);
        config.setTestOnBorrow(testOnBorrow);
        if (StringUtils.isEmpty(password)) {
            jedisPool =  new JedisPool(config, host, port, timeout);
        } else {
            jedisPool =  new JedisPool(config, host, port, timeout, password);
        }
        return jedisPool;
    }

 SpringMvc+redis实现session共享

1、Spring.xml文件配置



     



     
     



     
     
     
     
     
     
     

2、web.xml文件配置



    springSessionRepositoryFilter
    org.springframework.web.filter.DelegatingFilterProxy


    springSessionRepositoryFilter
    /webs/allow/*

 3、登录设置session,退出设置session无效

@PostMapping("/login.do")
public String login(String username, String password){
   request.getSession().setAttribute("user", user);
   return "登录成功";
}

@GetMapping("/logout.do")
public String logout(){
   HttpSession session = request.getSession();
   session.invalidate();
   return "退出成功";
}

 

你可能感兴趣的:(JAVA)