在微服务架构下,须要支持分布式Session,分布式Session能够经过Redis来实现,也能够经过数据库来实现,本文介绍Redis实现。java
下载地址:https://github.com/MSOpenTech...
选择对应的版本安装。 git
进入安装目录启动Redis。github
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency>
yml配置以下:web
# Redis服务器地址 spring.redis.host=localhost # Redis服务器链接端口 spring.redis.port=6379
config配置以下:redis
@Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400 * 30) public class SessionConfig { }
登录成功后设置Session信息,代码以下:spring
@Component @RestController public class LoginController { @RequestMapping("/login") public String login(@RequestBody String userId, HttpSession session) throws Exception { session.setAttribute(Constants.SESSION_USER_ID, userId); return "Login success."; } }
没有成功登录并设置Session,须要跳转到错误页面, 代码实例以下:数据库
@Configuration public class SessionFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (isNeedAuth(request)) { Object userIdObject = request.getSession().getAttribute(Constants.SESSION_USER_ID); if (null == userIdObject) { response.sendRedirect("/errorPage"); } } filterChain.doFilter(request, response); } }
以上为实现Redis Session的全部步骤,完整实例代码扫码加入微信公众号并回复:webfullstack,获取仓库地址。 apache
end.服务器
站点: http://javashizhan.com/微信
微信公众号:
<font color="#F4B183">加入知识星球,参与讨论,更多实战代码分享! </font>
https://t.zsxq.com/RNzfi2j