Tomcat利用Redis存储Session【单点redis和群集redis】

文章来源:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt269



如果英文不错的看,建议直接看官网吧,官网写的挺清楚。下面的内容是转载的一篇文章,自己补充了一些,供大家参考,也欢迎大家一起讨论

截止到2015-05-12前是不支持Tomcat8的,详情见官网:https://github.com/jcoleman/tomcat-redis-session-manager

前提:你已经部署了Redis,尚未学会的,可以移步这里:http://blog.csdn.net/caiwenfeng_for_23/article/details/45511007

其实很简单,就几个步骤: 
1.配置Tomcat的conf目录下的context.xml文件:

1> 单点Reids配置

1
2
3
4
5
6
7
<!-- Jedis save session -->
< Valve  className = "com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve"  />        
< Manager  className = "com.orangefunction.tomcat.redissessions.RedisSessionManager" 
     host = "localhost" 
     port = "6379" 
     database = "0" 
     maxInactiveInterval = "60" />

2> Sentinel集群配置:

<!-- Sentinel 配置 -->

<Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />        

<Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager" 

    maxInactiveInterval="60"

    sentinelMaster="mymaster"

    sentinels="127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381,127.0.0.1:26382" />

2.添加jar

这里写图片描述

3.测试

1> 
存储Session:

1
2
3
4
5
6
7
8
9
protected  void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException {
         System.out.println( "hello" );            //取得<a href="http://so.blog.yemou.net/cse/search?s=17470874779923938404&entry=1&q=Session%E5%AF%B9%E8%B1%A1" class="bdcs-inlinelink" target="_blank">Session对象</a>
         HttpSession session=request.getSession(); 
         //设置Session属性
         for (int i= 0 ;i< 100000 ;i++){
             session.setAttribute( "name" +i,  "Magci_" +i); 
         }
     }

2>重启Tomcat:假如Session保存在tomcat下,重启后Session不存在;如果保存在Redis下,Tomcat重启对Session无影响

3>取出Session:

1
2
3
4
5
6
7
8
9
  protected  void  doPost(HttpServletRequest request, HttpServletResponse response)
      throws  ServletException, IOException {
         System.out.println( "hello" );            //取得Session对象
         HttpSession session=request.getSession(); 
         //取出Session属性
         for ( int  i= 0 ;i< 100000 ;i++){
             System.out.println(session.getAttribute( "name" +i));
         }
     }

注意事项:从Tomcat6开始默认开启了Session持久化设置,测试时可以关闭本地Session持久化,其实也很简单,在Tomcat的conf目录下的context.xml文件中,取消注释下面那段配置即可:

1
2
3
4
  <!-- Uncomment this to disable session persistence across Tomcat restarts -->
     <!--
     <Manager pathname="" />
     -->

可以尝试运行上面的demo案例!

需要注意的是:

web.xml中的配置是有效的,即使是context.xml总配置maxInactiveInterval默认60秒,只要web.xml中的sessionConfig配置30分钟,则session的失效时间还是30分钟。

转自:http://blog.csdn.net/caiwenfeng_for_23/article/details/45666831


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值