spring-session 共享session

1.下载jar
<!-- spring 共享session -->
    <!-- https://mvnrepository.com/artifact/org.springframework.session/spring-session-data-redis -->
    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
        <version>1.3.1.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session</artifactId>
        <version>1.3.1.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-gemfire -->
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-gemfire</artifactId>
        <version>1.8.5.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-mongodb -->
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>1.9.4.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.lambdaworks/lettuce -->
    <dependency>
        <groupId>biz.paluch.redis</groupId>
        <artifactId>lettuce</artifactId>
        <version>3.5.0.Final</version>
    </dependency>

2.配置文件:


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd">


    <cache:annotation-driven/>
    <context:property-placeholder location="classpath:config/redis.properties"/>

    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="50"/>
        <property name="maxTotal" value="50"/>
        <property name="maxWaitMillis" value="50"/>
        <!--<property name="testOnBorrow" value="${redis.testOnBorrow}" />-->
    </bean>

    <!--<bean id="redisClient" class="redis.clients.jedis.JedisCluster">-->
    <!--<constructor-arg name="nodes">-->
    <!--<set>-->
    <!--<bean class="redis.clients.jedis.HostAndPort">-->
    <!--<constructor-arg name="host" value="192.168.6.24"></constructor-arg>-->
    <!--<constructor-arg name="port" value="6379"></constructor-arg>-->
    <!--</bean>-->
    <!--&lt;!&ndash;<bean class="redis.clients.jedis.HostAndPort">&ndash;&gt;-->
    <!--&lt;!&ndash;<constructor-arg name="host" value="192.168.31.100"></constructor-arg>&ndash;&gt;-->
    <!--&lt;!&ndash;<constructor-arg name="port" value="7001"></constructor-arg>&ndash;&gt;-->
    <!--&lt;!&ndash;</bean>&ndash;&gt;-->
    <!--</set>-->

    <!--</constructor-arg>-->
    <!--<constructor-arg name="poolConfig" ref="poolConfig"></constructor-arg>-->
    <!--</bean>-->

    <!--<bean id="redisClusterConfiguration" class=" org.springframework.data.redis.connection.RedisClusterConfiguration">-->
        <!--<property name="clusterNodes">-->
            <!--<set>-->
                <!--<value>192.168.6.24:3679</value>-->
                <!--<value>192.168.6.24:4679</value>-->
                <!--<value>192.168.6.24:5679</value>-->
            <!--</set>-->
        <!--</property>-->
    <!--</bean>-->

    <context:annotation-config />
    <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
    <!--<bean class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory"/>-->


    <bean id="connectionFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="poolConfig" ref="poolConfig"/>
        <property name="port" value="6379"/>
        <property name="hostName" value="192.168.6.24"/>
        <!--<property name="password" value="${redis.pass}" />-->
        <!--<property name="database" value="1" /> 数据库索引-->
        <property name="timeout" value="6000"/>
        <!--<constructor-arg name="clusterConfig" ref="redisClusterConfiguration"></constructor-arg>-->
    </bean>


    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="connectionFactory"/>
        <property name="keySerializer">
            <bean
                    class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
        <property name="valueSerializer">
            <bean
                    class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
        </property>
    </bean>





    <!-- 配置缓存 -->
    <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
        <constructor-arg ref="redisTemplate"/>
        <!--<property name="defaultExpiration" value="60" /> 默认缓存失效时间 60秒-->
        <property name="expires">
            <map>
                <entry key="demopo_update" value="180"/> <!--对缓存名称为demopo_update 设置时间1000秒-->
            </map>
        </property>
    </bean>


</beans>



3.配置web.xml
<!--使用spring session 中的redis begin  注意如果web.xml中有其他过滤器,
一般情况下Spring 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>
<!--使用spring session 中的redis end-->





4.编程测试:

package boce.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Calendar;

/**
* Created by gjp on 2017/7/20.
*/
@Controller
@RequestMapping("/session/")
public class SessionController {

    Logger logger = LoggerFactory.getLogger(SessionController.class);

    @RequestMapping(value = "setinfo")
    public ModelAndView sessionInfo(){
        ModelAndView mav = new ModelAndView("thymeleaf/setsession");
        ServletRequestAttributes servletRequestAttributes =(ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpSession session = servletRequestAttributes.getRequest().getSession();
        String value ="boce.com";
        String time1 = Calendar.getInstance().getTimeInMillis()+"";
        session.setAttribute("userId",value+time1);

        session.setAttribute("time1",time1);
        logger.info("session value="+value+time1);
        return mav;
    }


    @RequestMapping(value = "getinfo")
    public ModelAndView getInfo(){
        ModelAndView mav = new ModelAndView("thymeleaf/getsession");
        ServletRequestAttributes servletRequestAttributes =(ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpSession session = servletRequestAttributes.getRequest().getSession();
        String userId = (String) session.getAttribute("userId");
        String time = (String)session.getAttribute("time");
        mav.addObject("userId",userId);
        String sessionId = session.getId();
        long createTime = session.getCreationTime();
        long lastAccessedTime = session.getLastAccessedTime();
        int maxInactive = session.getMaxInactiveInterval();
        StringBuffer stringBuffer = new StringBuffer(64);
        stringBuffer.append("sessionId:").append(sessionId);
        stringBuffer.append(";createTime:").append(createTime);
        stringBuffer.append(";lastAccessdTime:").append(lastAccessedTime);
        stringBuffer.append("maxInactive:").append(maxInactive);

        logger.info(stringBuffer.toString());

        mav.addObject("time1",time);
        mav.addObject("good","good hello world!");
        logger.info("session value="+userId+";time1:"+time);
        return mav;
    }
}


测试结果:
.......
2017-07-21 11:23:22 INFO 11 [boce.common.mvcinterceptor.MVCRequestInterceptor] =preHandle end**********************
2017-07-21 11:23:22 INFO 33 [boce.demo.controller.SessionController] session value=boce.com1500607402364
............


2017-07-21 11:24:35 INFO 56 [boce.demo.controller.SessionController] sessionId:42b9e5d6-2a9f-4c0e-ae9e-2eb2ad1119cc;createTime:1500607429438;lastAccessdTime:1500607468057maxInactive:1800
2017-07-21 11:24:35 INFO 60 [boce.demo.controller.SessionController] session value=boce.com1500607429438;time1:null




猜你喜欢

转载自gjp014.iteye.com/blog/2386256