SpringSession+redis

先配置yml文件

server:
  port: 8080
  servlet:
    session:
      timneout: 3000

spring:
  application:
    name: SpringSessionRedis
  redis:
    host: localhost
    port: 6379
    timeout: 3000
    pool:
      max-idle: 8
      min-idle: 0
      max-active: 8
      max-wait: 1
  session:
    store-type: redis
    redis:
      #用于存储在redis中key的命名空间
      flush-mode: on_save
      #session更新策略,有ON_SAVE、IMMEDIATE,前者是在调用#SessionRepository#save(org.springframework.session.Session)时,在response commit前刷新缓存,
      #后者是只要有任何更新就会刷新缓存
      namespace: 'spring:session'

接下来实现一个拦截器

package com.springsesionredis.env;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


//拦截登录失效的请求
public class RedisSessionInterceptor implements HandlerInterceptor {
     
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     
        //无论访问的地址是不是正确的,都进行登录验证,登录成功后的访问再进行分发,404的访问自然会进入到错误控制器中
        HttpSession session = request.getSession();

        try {
     
            //验证当前请求的session是否是已登录的session
            String loginSessionId = redisTemplate.opsForValue().get("logUserId");
            System.out.println("loginSessionId=" + loginSessionId);

            if(loginSessionId != null && !"".equals(loginSessionId)) {
     
                return true;
            }
        }
        catch (Exception e) {
     
            e.printStackTrace();
        }

        response401(response);
        return false;
    }

    private void response401(HttpServletResponse response) {
     

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        try {
     
            response.getWriter().print("未登陸");
        } catch (IOException e) {
     
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
     

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
     

    }
}

把这个拦截器加到环境中

package com.springsesionredis.env;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebSecurityConfig implements WebMvcConfigurer {
     
   @Bean
   public RedisSessionInterceptor getSessionInterceptor()
   {
     
       return new RedisSessionInterceptor();
   }

   @Override
   public void addInterceptors(InterceptorRegistry registry)
   {
     
       //所有已api开头的访问都要进入RedisSessionInterceptor拦截器进行登录验证,并排除login接口(全路径)。必须写成链式,分别设置的话会创建多个拦截器。
       //必须写成getSessionInterceptor(),否则SessionInterceptor中的@Autowired会无效
       registry.addInterceptor(getSessionInterceptor()).addPathPatterns("/api/**").excludePathPatterns("/api/user/login");
   }
}

弄一个helloAction作为测试

package com.springsesionredis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
//@Controller
//@RequestMapping("helloAction")
public class HelloAction {
     

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/hello")
    //@RequestMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
     
        return String.format("Hello %s!", name);
    }

    @GetMapping("/api/test01")
    public String test01() {
     
        return "hello world";
    }

    @GetMapping("/api/user/login")
    public String login(HttpServletRequest request, String userName, String pwd) {
     

        HttpSession session = request.getSession();
        session.setAttribute("logUserId", userName);
        redisTemplate.opsForValue().set("logUserId", userName);
        return session.getId();
    }
}

最后搞一个启动类

package com.springsesionredis;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
     

    public static void main(String[] args) {
     
        SpringApplication.run(Application.class);
    }
}

你可能感兴趣的:(SpringCloud开发,java开发,spring,boot,redis,session)