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

1、分布式Session的Redis实现

在微服务架构下,须要支持分布式Session,分布式Session能够经过Redis来实现,也能够经过数据库来实现,本文介绍Redis实现。java

2、安装Redis

下载地址:https://github.com/MSOpenTech...
选择对应的版本安装。 git

进入安装目录启动Redis。github

3、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>

4、yml配置

yml配置以下:web

# Redis服务器地址
spring.redis.host=localhost
# Redis服务器链接端口
spring.redis.port=6379

5、Config配置

config配置以下:redis

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400 * 30)
public class SessionConfig {

}

6、登录后设置Session

登录成功后设置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.";
    }
}

7、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,获取仓库地址。 apache

end.服务器


站点: http://javashizhan.com/微信


微信公众号:
图片描述


<font color="#F4B183">加入知识星球,参与讨论,更多实战代码分享! </font>
https://t.zsxq.com/RNzfi2j
图片描述

相关文章
相关标签/搜索