共计 1636 个字符,预计需要花费 5 分钟才能阅读完成。
一、分布式 Session 的 Redis 实现
在微服务架构下,需要支持分布式 Session,分布式 Session 可以通过 Redis 来实现,也可以通过数据库来实现,本文介绍 Redis 实现。
二、安装 Redis
下载地址:https://github.com/MSOpenTech…
选择对应的版本安装。
进入安装目录启动 Redis。
三、pom 文件
<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 配置
yml 配置如下:
# Redis 服务器地址
spring.redis.host=localhost
# Redis 服务器连接端口
spring.redis.port=6379
五、Config 配置
config 配置如下:
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400 * 30)
public class SessionConfig {}
六、登陆后设置 Session
登陆成功后设置 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 鉴权过滤器
没有成功登陆并设置 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.
站点:http://javashizhan.com/
微信公众号:
<font color=”#F4B183″> 加入知识星球,参与讨论,更多实战代码分享!</font>
https://t.zsxq.com/RNzfi2j
正文完