给Spring session配置基于redis来存储session数据,然后配置了一个Spring session的过滤器,这样的话,session相关操作都会交给Spring session来管了,接着在代码中,就用原生的session操作,就是基于Spring session从redis中获取数据了。
导入依赖
<!--spring 版本-->
<spring.version>5.0.2.RELEASE</spring.version>
<spring.session.data.redis.version>1.3.1.RELEASE</spring.session.data.redis.version>
<lettuce.version>3.5.0.Final</lettuce.version>
<!-- spring web包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>${spring.session.data.redis.version}</version>
</dependency>
<dependency>
<groupId>biz.paluch.redis</groupId>
<artifactId>lettuce</artifactId>
<version>${lettuce.version}</version>
</dependency>
编写redis配置文件
redis.host=192.168.80.22
redis.pass=myredis
redis.port=6379
redis.session.timeout=600
编写spring配置文件
<?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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<!-- 加载properties文件 -->
<bean id="configProperties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:session-redis.properties</value>
</list>
</property>
</bean>
<!-- RedisHttpSessionConfiguration -->
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
<!-- session过期时间,单位是秒 -->
<property name="maxInactiveIntervalInSeconds" value="${redis.session.timeout}" />
</bean>
<!--LettuceConnectionFactory -->
<bean class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory"
p:host-name="${redis.host}" p:port="${redis.port}" />
</beans>
配置web.xml
拦截器拦截请求后,web请求中的request已经不一样了,但是用法一样
<!--加载spring配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext-session.xml</param-value>
</context-param>
<!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置过滤器(该过滤器要配置在第一的位置)-->
<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>
标签:web,spring,redis,springframework,session,Spring
From: https://blog.51cto.com/u_15973676/6069322