Spring boot session redis封装了redis的存取,只要引用jar包、配置好redis(单机或集群),就会自动使用redis进行session缓存、读取。使用简单的session应用时感觉不到redis的存在。
1、准备好redis
2、引入jar
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
3、拦截器
package com.zyf.demo.interceptor;
import com.zyf.demo.domain.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class Interceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
User user = (User) request.getSession().getAttribute("user");
if (null != user) {
return true;
}
response.sendRedirect(request.getContextPath() + "/");
return false;
}
}
4、添加到配置
package com.zyf.demo.config;
import com.zyf.demo.interceptor.Interceptor;
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 MyConifg implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new Interceptor()).addPathPatterns("/**").excludePathPatterns("/user/login");
}
}
5、就可以直接登录校验、使用session了
@RequestMapping("/test")
@ResponseBody
public Object test(HttpServletRequest request){
HttpSession session = request.getSession();
Object o = session.getAttribute("name");
Object o1 = session.getAttribute("user");
return o+"<br>"+o1;
}
这只是最简单的一个拦截器使用,具体跟据需求来做。
如果不引用该jar,session就存到容器了,也就是单机模式了。