Session(会话),用来记录信息确定用户身份,保存在服务端。当客户端浏览器访问服务器时,服务器会把客户端信息保存在服务器上,这个就是Session。和Session对应的是Cookie,Cookie也是记录信息确定用户身份的,不同的是,Cookie存储在客户端,Session存储在服务端。一般会结合使用,Session存储重要信息,次要信息使用Cookie存储。
对比:
Session Cookie 存储在服务端 存储在客户端 安全性高 安全性低,存储在客户端,可以获取进行分析 访问增多时,会占用服务器性能 保存在客户端,会减轻服务器压力 支持任意大小、类型的数据 数据不能超过4K,并且多数浏览器会显示Cookie个数
在分布式系统中,我们需要考虑分布式事务、接口幂等性、分布式锁、分布式Session等等。分布式事务我们可以使用阿里巴巴开源的seata框架解决,今天我们就来讲讲分布式Session。
不使用Session
我们可以使用Token存储用户信息,使用时从数据库、缓存中读取,例如存储在redis中,这样请求无论到哪个服务器,我们都可以读取到用户信息。也可以使用JWT,可以将用户信息加密到Token交给客户端存储,服务端不保存任何用户信息,只进行验证。
使用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"/>
使用Spring Session+Redis
我们可以使用Spring Session和Redis实现共享存储Session,这样就不依赖部署的Web容器。下面我们简单讲解一些配置和使用,感兴趣的小伙伴可以动手试试。
依赖:pom.xml
<dependency>
<groupId>org.springframework.sessiongroupId>
<artifactId>spring-session-data-redisartifactId>
<version>1.2.1.RELEASEversion>
dependency>
<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
<version>2.8.1version>
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>springSessionRepositoryFilterfilter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
filter>
<filter-mapping>
<filter-name>springSessionRepositoryFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
原文链接:https://monkey.blog.xpyvip.top/archives/fen-bu-shi-session-ru-he-cun-chu