spring session + redis 实现web工程的session共享

27 篇文章 0 订阅
18 篇文章 0 订阅

http://blog.csdn.net/sdmanooo/article/details/55211166

关于session共享,在网上有很多文章,但是很少有文章是别人看过了,能够实际操作就能实现出来的,我不知道是文章写的漏掉了什么还是什么原因,可能是我的能力还达不到文章所需要的能力要求吧。先不管那么多了,我就以我实际配置安装部署的实例来讲述下我的实现session共享的方式吧。

文章开始之前,先讲点小插曲。一开始我是想不对程序做任何改动的情况下,只通过nginx+tomcat+redis的方式进行实现session共享,实际配置之后,用简单的测试session的一个jsp页面进行测试,的确看得出session是共享的。但是当真正部署上我的web工程(spring+springMVC+mybatis)之后,发现session并不能共享,session的内容也不往redis里输出,找不出什么原因,最终放弃了这种做法,决定用spring自带的session管理借助redis来实现session共享,此操作只需要改些配置,改jar包,不需要改动业务代码。

首先,明确一下环境要求:windows系统,1.7jdk,tomcat7,使用spring-session,要求spring的相关依赖包必须是spring4.0以上,redis要求是3.0以上。项目工程中除了spring基础的一些核心包之外,需要额外引入commons-pool2-2.4.2.jar,jedis-2.7.3.jar,spring-data-redis-1.6.2.RELEASE.jar,spring-session-1.1.1.RELEASE.jar,相应的版本号也给出了,起码这些版本的jar包在一起使用,是相互兼容可用的,我不敢保证其他版本的jar包引入之后会不会有什么问题,大家有兴趣可以尝试一下其他版本的。

在此也贴一下spring+session相关jar包的下载地址:http://download.csdn.net/detail/sdmanooo/9755249。

redis3.0的下载地址:http://download.csdn.net/detail/sdmanooo/9755259    下载解压之后,在目录中运行cmd,执行redis-server.exe redis.windows.conf 进行启动redis,不能直接双击redis-server.exe,否则不读取conf配置。


其实整个过程梳理一下也很简单。

一、工程要整合spring-session

1.引入所需的jar包

2.web.xml中添加

<filter>
     <filter-name>springSessionRepositoryFilter</filter-name>
     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
   </filter>
  <filter-mapping>
    <filter-name>springSessionRepositoryFilter</filter-name>
     <url-pattern>/*</url-pattern>
   </filter-mapping>

网上有说如果有其他的filter需要将此段代码放到所有filter的前面,其实没这个必要。

3. applicationContext.xml中添加

<!-- session设置 -->
     <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
         <property name="maxInactiveIntervalInSeconds" value="3600"></property>
     </bean>
     <!-- redis连接池 -->
     <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"/>
 
     <!-- redis连接工厂 -->
     <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
         <property name="hostName" value="127.0.0.1"/>
         <property name="port" value="6379"/>
         <property name="password" value=""/>
         <property name="timeout" value="20000"/>
         <property name="poolConfig" ref="poolConfig"></property>
     </bean>

由于我是本地的redis,也没有设置密码,所以是127.0.0.1,端口默认6379,可根据redis的地址自行调整。

至此,程序的session共享已经完成,只要保证能正常启动即可,启动时,需要redis先启动,否则会报错。


二、搭建集群环境测试

1. 配置nginx

我的两个tomcat的端口分别是20001和21001,所以nginx的配置如下:

upstream local_tomcat{
server 127.0.0.1:20001 weight=5;
server 127.0.0.1:21001 weight=5;
}

server {
        listen       80;
        server_name  localhost;

location / {
proxy_pass http://local_tomcat;
proxy_set_header   Host             $host;  
proxy_set_header   X-Real-IP $remote_addr;  
            proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for; 
}

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

nginx根目录下启动cmd,执行start nginx 即可启动nginx。可从进程中查看nginx是否正常启动。


2. 测试session

可以在工程的主页面上输出一下<%= session.getId() %>,

为了区分tomcat,我在20001tomcat下的工程的主页面上还输出了1111

21001tomcat下工程的主页面上输出了2222。

在浏览器中,访问localhost/工程名/主页面

不停的F5刷新页面,即可看到<%= session.getId() %>的值是不变的,但是tomcat是不断的在切换的。


使用SpringBoot框架结合MyBatis实现Session共享和单点登录可以借助SpringSessionRedis实现。 首先,需要配置SpringSession以使用Redis作为存储方式。可以在SpringBoot的配置文件中添加以下配置: ``` spring.session.store-type=redis spring.session.redis.namespace=spring:session spring.redis.host=127.0.0.1 spring.redis.port=6379 ``` 这样配置后,SpringSession会自动将session信息存储到Redis中。 接着,在登录验证成功后,将用户信息存储到Redis中,并将该用户的唯一标识存储到当前Session的属性中,以便后续验证是否登录。例如: ``` @RequestMapping("/login") public String login(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session) { // 验证用户名和密码 // ... // 验证通过后,将用户信息存储到Redis中,并设置Session属性 redisTemplate.opsForHash().put("user:" + username, "username", username); session.setAttribute("username", username); return "success"; } ``` 在后续的请求中,可以通过拦截器或过滤器来验证Session是否有效。例如: ``` @Component public class SessionInterceptor implements HandlerInterceptor { @Autowired private RedisTemplate<String, Object> redisTemplate; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); String username = (String) session.getAttribute("username"); if (StringUtils.isEmpty(username)) { response.sendRedirect("/login"); return false; } String storedUsername = (String) redisTemplate.opsForHash().get("user:" + username, "username"); if (!StringUtils.equals(storedUsername, username)) { response.sendRedirect("/login"); return false; } return true; } } ``` 以上代码片段展示了如何通过拦截器验证Session的有效性。首先从当前Session中获取用户名,如果为空则重定向到登录页面。然后从Redis中获取存储的用户名,如果与当前用户名不匹配,则重定向到登录页面。 这样就实现SpringBoot、MyBatis、SpringSessionRedis共同完成Session共享和单点登录的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值