淘先锋技术网

首页 1 2 3 4 5 6 7

利用spring的RedisTemplate实现session的存取,先配置applicationContext-shiro.xml

<!-- 会话管理器 -->
    <bean id="sessionManager"
          class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <property name="sessionValidationInterval" value="1800000"/>  <!-- 相隔多久检查一次session的有效性 -->
        <property name="globalSessionTimeout" value="1800000"/>
        <property name="deleteInvalidSessions" value="true"/>
        <property name="sessionValidationSchedulerEnabled" value="true"/><!-- 定时检查失效的session -->
        <!--<property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>-->
        <property name="sessionDAO" ref="sessionDAO"/>
        <!--<property name="sessionIdCookie" ref="simpleCookie"/>-->
        <property name="sessionIdCookie.name" value="shiro.sesssion"/>
        <property name="sessionIdCookie.path" value="/"/>
        <property name="sessionIdCookieEnabled" value="true"/>
        <!--<property name="sessionIdCookie" ref="sessionIdCookie" />-->
    </bean>
    <!-- 会话DAO -->
    <bean id="sessionDAO" class="com.ogmall.web.manager.cache.RedisSessionDao">
        <property name="redisTemplate" ref="redisObjectTemplate"></property>
    </bean>
<bean id="redisObjectTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory"/>
        <!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!!  -->
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
        </property>
        <property name="hashKeySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
        <property name="hashValueSerializer">
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
        </property>
    </bean>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="600"></property>
        <property name="maxIdle" value="300"></property>
        <property name="minIdle" value="10"></property>
        <property name="maxWaitMillis" value="2000"></property>

        <property name="testOnBorrow" value="true"></property>
        <property name="testOnReturn" value="true"></property>
    </bean>
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="192.168.1.149"/>
        <property name="port" value="6379"/>
        <property name="poolConfig" ref="jedisPoolConfig"></property>
        <!--<property name="timeout" value="5000"></property>-->
        <property name="usePool" value="true"></property>
        <!--<property name="password" value="" />-->
        <property name="database" value="10"/>
    </bean>
RedisSessionDao.java

package com.ogmall.web.manager.cache;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/6/30 0030.
 */
public class RedisSessionDao extends AbstractSessionDAO {
    private RedisTemplate redisTemplate;

    Logger log= LoggerFactory.getLogger(getClass());
    /**
     * The Redis key prefix for the sessions
     */
    private String keyPrefix = "shiro_redis_session_manager:";
    private String getKey(String originalKey) {
        return keyPrefix+originalKey;
    }
    @Override
    public void update(Session session) throws UnknownSessionException {
//        log.info("更新seesion,id=[{}]",session.getId().toString());
        try {
            redisTemplate.opsForValue().set(getKey(session.getId().toString()), session,30, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }
    @Override
    public void delete(Session session) {
        log.info("删除seesion,id=[{}]",session.getId().toString());
        try {
            String key=getKey(session.getId().toString());
            redisTemplate.delete(key);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    @Override
    public Collection<Session> getActiveSessions() {
        log.info("获取存活的session");
//        System.out.println(redisTemplate.opsForValue().get("shiro_redis_session_manager:*"));
        return Collections.emptySet();
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        log.info("创建seesion,id=[{}]",session.getId().toString());
        try {
            redisTemplate.opsForValue().set(getKey(session.getId().toString()), session,30,TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
//        log.info("获取seesion,id=[{}]",sessionId.toString());
        Session session = null;
        try {
            session=(Session) redisTemplate.opsForValue().get(getKey(sessionId.toString()));
//            System.out.println(System.currentTimeMillis()+"-"+session.getLastAccessTime().getTime()+"="+(System.currentTimeMillis()- session.getLastAccessTime().getTime()));
//            if((System.currentTimeMillis()- session.getLastAccessTime().getTime())>1800000L){//30分钟没登录 过期
//                System.out.println("删除");
//                delete(session);
//                return null;
//            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return session;
    }
    public RedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}