SpringSession优点html
关键点在于作到透明和兼容html5
基本环境需求java
进行使用Spring Session的话,首先的是已经安装好的有一个 Redis服务器!web
添加项目依赖(最基本的依赖使用)redis
<!--Spring Session--> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> <version>1.3.0.RELEASE</version> <type>pom</type> </dependency>
(3)添加Spring配置文件spring
添加了必要的依赖以后,咱们须要建立相应的Spring配置。Spring配置是要建立一个Servlet过滤器,它用Spring Session支持的HttpSession实现来替换容器自己HttpSession实现。这一步也是Spring Session的核心。api
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="127.0.0.1"/>
<property name="port" value="6379"/>
<property name="password" value=""/>
</bean>
在web.xml中添加DelegatingFilterProxy(必定要放在自定义filter以前,否则会出现自定义filter中没法获取到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>
DelegatingFilterProxy将经过springSessionRepositoryFilter的名称查找Bean并将其转换为过滤器。对于调用DelegatingFilterProxy的每一个请求,也将调用springSessionRepositoryFilter。服务器
使用工具查看Redis内容:session
对于分布式环境Session跨域共享的问题,无论是使用开源的框架仍是使用本身开发的框架,都须要明白的一个问题是:在Tomcat容器中建立Session是一个很耗费内存的事情。所以,咱们在本身写相似框架的时候,咱们必定要注意的是,并非Tomcat为咱们建立好了Session以后,咱们首先获取Session而后再上传到Redis等进行存储,而是直接有咱们本身建立Session,这一点是相当重要的!
关于Error creating bean with name ‘enableRedisKeyspaceNotificationsInitializer’错误的处理:
添加以下配置让Spring Session再也不执行config命令
<util:constant static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP"/>
若是不添加的话,会报以下错误:
Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'enableRedisKeyspaceNotificationsInitializer' defined in class path resource [org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.class]:
Invocation of init method failed; nested exception is java.lang.IllegalStateException: Unable to configure Redis to keyspace notifications.
See http://docs.spring.io/spring-session/docs/current/reference/html5/#api-redisoperationssessionrepository-sessiondestroyedeventCaused by: redis.clients.jedis.exceptions.JedisDataException: ERR unknown command config