spring-session-data-redis 不工作

spring-session-data-redis not working

我试过官方参考提供的例子Spring Session. After login via http://localhost:8080/login session数据好像还在内存中,没有redis交互(通过redis-cli monitor命令观察)。只有 JSESSIONID 存储在 cookies

设置如下:

web.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

spring.xml:

<context:annotation-config/>
<beans:bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
<beans:bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
            p:hostName="192.168.1.230"
            p:port="6379"
/>

<security:authentication-manager>
    <security:authentication-provider>
        <security:user-service>
            <security:user name="root" password="123456" authorities="ROLE_ADMIN"/>
        </security:user-service>
    </security:authentication-provider>
</security:authentication-manager>
<security:global-method-security secured-annotations="enabled"/>
<security:http auto-config="true">
    <security:intercept-url pattern="/ping" access="hasRole('ROLE_ADMIN')"/>
    <security:form-login default-target-url="/ping"/>
    <security:csrf disabled="true"/>
</security:http>

<mvc:annotation-driven/>

<context:component-scan base-package="io.hbprotoss.demo.controller"/>

您需要声明会话存储库过滤器,如下所示:

<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>

由于您正在使用 spring 安全性,因此请确保在 安全性过滤器(以及任何其他可能想要访问session 否则你可能会得到两个会话,一个由 servlet 容器提供,另一个由 spring session.

可以在此处找到更多详细信息 https://docs.spring.io/spring-session/docs/current/reference/html5/#xml-servlet-container-initialization