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

一、分布式Session的Redis实现

在微服务架构下,需要支持分布式Session,分布式Session可以通过Redis来实现,也可以通过数据库来实现,本文介绍Redis实现。

二、安装Redis

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

进入安装目录启动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/


微信公众号:
在这里插入图片描述


加入知识星球,参与讨论,更多实战代码分享!
https://t.zsxq.com/RNzfi2j
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值