设为首页 加入收藏

TOP

分布式Session如何存储
2023-07-25 21:27:09 】 浏览:31
Tags:Session 何存储

分布式Session如何存储

一、介绍

Session(会话),用来记录信息确定用户身份,保存在服务端。当客户端浏览器访问服务器时,服务器会把客户端信息保存在服务器上,这个就是Session。和Session对应的是Cookie,Cookie也是记录信息确定用户身份的,不同的是,Cookie存储在客户端,Session存储在服务端。一般会结合使用,Session存储重要信息,次要信息使用Cookie存储。

对比:

Session Cookie
存储在服务端 存储在客户端
安全性高 安全性低,存储在客户端,可以获取进行分析
访问增多时,会占用服务器性能 保存在客户端,会减轻服务器压力
支持任意大小、类型的数据 数据不能超过4K,并且多数浏览器会显示Cookie个数

二、分布式Session

在分布式系统中,我们需要考虑分布式事务、接口幂等性、分布式锁、分布式Session等等。分布式事务我们可以使用阿里巴巴开源的seata框架解决,今天我们就来讲讲分布式Session。

三、实现方式

  1. 不使用Session

    我们可以使用Token存储用户信息,使用时从数据库、缓存中读取,例如存储在redis中,这样请求无论到哪个服务器,我们都可以读取到用户信息。也可以使用JWT,可以将用户信息加密到Token交给客户端存储,服务端不保存任何用户信息,只进行验证。

  2. 使用Tomcat+Redis

    我们可以在Tomcat的配置文件中进行设置,设置成功之后,Tomcat会将Session存储到Redis中,这样我们访问不通的Tomcat时,可以保证session是共享的。

    context.xml文件

    <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />
    
    <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
             host="127.0.0.1"
             port="6379"
             database="0"
             maxInactiveInterval="60"/>
    
  3. 使用Spring Session+Redis

    我们可以使用Spring Session和Redis实现共享存储Session,这样就不依赖部署的Web容器。下面我们简单讲解一些配置和使用,感兴趣的小伙伴可以动手试试。

    依赖:pom.xml

    <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
            <version>1.2.1.RELEASE</version>
    </dependency>
    <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.1</version>
    </dependency>
    

    配置文件:

    <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
    
    <bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="127.0.0.1" />
        <property name="password" value="123654" />
        <property name="port" value="6379" />
        <property name="database" value="0" />
    </bean>
    

    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>
    

原文链接:https://monkey.blog.xpyvip.top/archives/fen-bu-shi-session-ru-he-cun-chu

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇求求你们了,别再重复造轮子了,.. 下一篇CopyOnWriteArrayList与CopyOnWri..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目