使用Spring-Session共享使用Session_在spring context中添加db session-程序员宅基地

技术标签: reids  Linux  session共享  Spring-session  SpringMVC  整合springsession  

前言:

session共享策略有很多,常见的有粘性复制,高并发下效率查。tomcat-redis-session-manager无疑是一个挺好的方案,缺点要配置tomcat,有点复杂。最优的方案莫过于使用Spring-Session无缝整合redis,只要项目修改即可。

测试项目结构:

项目结构很简单:
这里写图片描述

Test.java 就是一个页面跳转,传输一下sessionid

@Controller
public class Test {
    
    @RequestMapping("/test")
    public String test(HttpSession session, HttpServletRequest request) {
        request.setAttribute("id", session.getId());
        return "index";
    }

}

index.jsp 单纯的打印一下sessionid

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%-- <%@ page isELIgnored ="false" %>   --%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'TestUpload.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>

<body>
我的session:${id}
    <br> sessionid=<%=session.getId()%>

</body>
</html>

当项目部署到nginx上的两个tomcat上时,每次访问地址,打印出来的sessionId都发生变化,这样在一些登录的操作中,用户明明在tomcatA上登录了,但是用户的其他操作负载到了TomcatB中,然而B不知道用户已经在A登录了,又让用户登录一次,这样用户体验极差。使用Spring-Session就是把用户的session缓存到redis中,让大家都从redis中获取用户session,这样就保证了session的共享。

使用Spring-Session

  • pom.xml 增加依赖
<!-- 使用Spring Session来解决Session共享问题  -->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
            <version>1.3.0.RELEASE</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>biz.paluch.redis</groupId>
            <artifactId>lettuce</artifactId>
            <version>3.5.0.Final</version>
        </dependency>
  • web.xml增加配置
<!-- Spring session -->
    <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>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>ERROR</dispatcher>
    </filter-mapping>
  • Spring.xml增加配置
    作用是导入redis配置redis.properties,导入新建的一个配置文件spring-session.xml
<context:property-placeholder location="classpath:db.properties,classpath*:redis.properties" ignore-unresolvable="true"/>
...
<import resource="classpath:spring-session.xml"/>
  • 新增配置spring-session.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd   http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- 创建名为springSessionRepositoryFilter 的Spring Bean,继承自Filter。 springSessionRepositoryFilter替换容器默认的HttpSession支持为Spring 
        Session, 将Session实例存放在Redis中 -->
    <bean id="redisHttpSessionConfiguration"
        class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration" />

    <!-- 使用LettuceConnectionFactory -->
    <bean
        class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory">
        <property name="hostName" value="${redis.ip}" />
        <property name="port" value="${redis.port}" />
        <property name="password" value="${redis.password}" />
    </bean>

    <!-- 也可以将使用LettuceConnectionFactory改成使用JedisConnectionFactory,两者保留其一就好 -->
    <!--<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> -->
    <!--<property name="hostName" value="${redis.ip}"/> -->
    <!--<property name="port" value="${redis.port}"/> -->
    <!--<property name="password" value="${redis.password}"/> -->
    <!--</bean> -->

    <!-- 让Spring Session不再执行config命令 -->
    <!-- <util:constant
        static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP" /> -->

</beans>
  • 增加redis.properties

redis.ip=193.112.76.194
redis.port=6379
redis.password=xxxxxx
redis.pool.maxTotal=10
redis.pool.minIdle=4
redis.pool.maxIdle=8
redis.pool.testOnBorrow=true

发布到服务器上。访问index页面。无论刷新多少次结果都一样。session没变

我的session:a4b2fe35-aaa5-40c2-a7de-b1d60180ca04
sessionid=a4b2fe35-aaa5-40c2-a7de-b1d60180ca04

使用redis客户端查看

这里写图片描述

刚好有个seession一致。

原理:

DelegatingFilterProxy拦截器拦截, springSessionRepositoryFilter替换容器默认的HttpSession支持为SpringSession每个请求都会访问它。

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_35830949/article/details/79995318

智能推荐

ZMON-程序员宅基地

文章浏览阅读2.4k次。https://opensource.zalando.com/zmon/ Checks and Alerts Define checks executed on self defined entities. Define aler..._zmon

layui表格添加链接列_Layui表格列添加超链接-程序员宅基地

文章浏览阅读3.4k次。记录一下,需要用到templet属性,也就是自定义列模板参考代码:{ field: 'oddNumbers', width: 180, title: '单号', sort: true, fixed: 'left', templet: addLink },addLink是个方法function addLink(d) {var addLink = d.oddNumbers;if ('' == addL..._layui table 单元格超链接

计算机科学与技术有web设计,Web-Sites-Design-and-Programming-6计算机科学与技术---网站设计与编程--双语教学课件...-程序员宅基地

文章浏览阅读121次。《Web-Sites-Design-and-Programming-6计算机科学与技术---网站设计与编程--双语教学课件》由会员分享,可在线阅读,更多相关《Web-Sites-Design-and-Programming-6计算机科学与技术---网站设计与编程--双语教学课件(29页珍藏版)》请在人人文库网上搜索。1、Web Sites Design and Programming,Lectur..._web sites design and programming

简单jQuery插件实现_e会学插件-程序员宅基地

文章浏览阅读428次。【前言】 本文是转载http://www.cnblogs.com/fromearth/archive/2009/07/08/1519054.html 这个来学的,我还是很仰慕这些大神,他们0几年的博客,我现在学起来还感觉获益匪浅,我只是把他的代码,敲出来而已,并且做了一点修改,在这里写出来希望对大家有用,再次感谢那些大神。【实践】 jQuery开发或使用,更多的灵感是来自实践,而不是copy_e会学插件

如何将本地Jar包添加到本地的Maven仓库_obdriver-1.0.1-程序员宅基地

文章浏览阅读6.1k次,点赞2次,收藏21次。一、问题描述项目开发过程中,经常遇到项目缺少依赖的问题。这些Jar包无法从远程仓库中下载,究其原因有以下几点:(1)依赖的Jar包是与该项目关联的公司其他项目(2)依赖的Jar包是其他公司开发,并未发布到远程仓库(3)网络原因导致从远程仓库中无法下载Jar包二、解决方案需要将依赖的Jar包从其他途径下载到本地,然后添加到本地仓库。这样在每次构建项目就能够从本地加载到依赖的Jar包。三、操作方法1.打开命令行cmd窗口2.执行mvn install以阿里的oceanba_obdriver-1.0.1

CTA-敏感行为-读取剪切板_read_clipboard_in_background-程序员宅基地

文章浏览阅读768次。Android 源码国内: AndroidXRef(1.6-9.0) AOSPXRef(7.1-12.0) 海外: https://android.googlesource.com/platform/frameworks/base/ Android 文档国内 文档:Documentation | Android 开发者 | Android Developers 指南:开发者指南 | Android 开发者 | Android Developers 参考文..._read_clipboard_in_background

随便推点

java的jdk安装错误_记录一个jdk安装错误 error: open of failed:No such file or directory-程序员宅基地

文章浏览阅读1.9k次。今天在一台新机器, 采用rpm方式安装jdk,rpm -ivh jdk-8u181-linux-i586.rpm安装过程发生了错误, 错误信息包含大量的html相关信息:error: open of failed: No such file or directoryerror: open of failed: No such file or directoryerror: open of U..._error: open of –force failed: no such file or directory

BZOJ 2395 Balkan 2011 Time is Money 最小乘积生成树_bzoj 2395time is money-程序员宅基地

文章浏览阅读758次。网上题解讲的好清楚好清楚了。。令x=∑c,y=∑tx=\sum c,y=\sum t,要最优化xyxy,如果将其表示成(x,y)(x,y),那么最优的(x,y)(x,y)只会在下凸壳上,那么分治? 分治将凸壳不断地划分,至于划分点有一个很显然的在凸壳上的就是离两端点最远的点C(在坐标轴侧)。 求C显然是最大化S△ABC=12AB×d=12AC−→−×AB−→S_{\triangle ABC}=\_bzoj 2395time is money

CentOS6/CentOS7 双网卡配置bonding_centos6 配置双网卡-程序员宅基地

文章浏览阅读8.7k次,点赞4次,收藏24次。CentOS6/CentOS7 双网卡配置bonding在CentOS6/RHEL6上配置网络绑定 网络绑定是将多个局域网卡(eth0和eth1)聚合成称为绑定接口的单个接口。 网络绑定是一项内核功能,也称为网卡绑定。 通常需要绑定来提供高可用性和负载均衡服务。 在本教程中,笔者在CentOS 6.X上配置网络绑定,笔者服务器有两个Lan卡(em1和em2)并将创建绑定接..._centos6 配置双网卡

LeetCode 215. 数组中的第K个最大元素_leetcode215 o(n)-程序员宅基地

文章浏览阅读301次。题目在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。示例 1:输入: [3,2,1,5,6,4] 和 k = 2 输出: 5 示例 2:输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 输出: 4 说明:你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。思路该题的..._leetcode215 o(n)

PTA-浙大版《C语言程序设计(第3版)》题目集-函数题代码(一)_浙江大学pta读者码共享-程序员宅基地

文章浏览阅读1.6k次,点赞4次,收藏31次。PTA—浙大版《C语言程序设计(第3版)》题目集—函数题代码(一)_浙江大学pta读者码共享

DNA Sorting(水题)_dna sorting oj-程序员宅基地

文章浏览阅读1k次。DescriptionOne measure of ``unsortedness'' in a sequence is the number of pairs of entries that are out of order with respect to each other. For instance, in the letter sequence ``DAABEC'', this measu..._dna sorting oj

推荐文章

热门文章

相关标签