Web应用全栈之旅-Spring篇(一)分布式Session

一、分布式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/

微信公众号:
《Web应用全栈之旅-Spring篇(一)分布式Session》

<font color=”#F4B183″>加入知识星球,参与讨论,更多实战代码分享! </font>
https://t.zsxq.com/RNzfi2j
《Web应用全栈之旅-Spring篇(一)分布式Session》

    原文作者:飞流
    原文地址: https://segmentfault.com/a/1190000020037599
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞