在微服务架构下,需要支持分布式Session,分布式Session可以通过Redis来实现,也可以通过数据库来实现,本文介绍Redis实现。
下载地址:https://github.com/MSOpenTech...
选择对应的版本安装。
进入安装目录启动Redis。
<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配置如下:
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
config配置如下:
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400 * 30)
public class SessionConfig {
}
登陆成功后设置Session信息,代码如下:
@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,获取仓库地址。
end.
微信公众号:
加入知识星球,参与讨论,更多实战代码分享!
https://t.zsxq.com/RNzfi2j
声明:该文章系转载,转载该文章的目的在于更广泛的传递信息,并不代表本网站赞同其观点,文章内容仅供参考。
本站是一个个人学习和交流平台,网站上部分文章为网站管理员和网友从相关媒体转载而来,并不用于任何商业目的,内容为作者个人观点, 并不代表本网站赞同其观点和对其真实性负责。
我们已经尽可能的对作者和来源进行了通告,但是可能由于能力有限或疏忽,导致作者和来源有误,亦可能您并不期望您的作品在我们的网站上发布。我们为这些问题向您致歉,如果您在我站上发现此类问题,请及时联系我们,我们将根据您的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。
微信扫码关注 HaowuliaoA 订阅号