使用Redis实现Session共享

Maven依赖

<!-- Shiro核心包 -->
	<dependency>
		<groupId>org.apache.shiro</groupId>
		<artifactId>shiro-core</artifactId>
		<version>1.2.3</version>
	</dependency>
	<dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.2.3</version>
        </dependency>
 
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.2.2</version>
        </dependency>
 
<!-- redis -->
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.5.0</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>1.6.2.RELEASE</version>
    </dependency>
 

redis.properties

#访问地址
redis.host=192.168.1.12
#访问端口
redis.port=6379
#注意,如果没有password,此处不设置值,但这一项要保留
redis.password=123456

#最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。
redis.maxIdle=300
#最小空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。
redis.minIdle=8
#连接池的最大数据库连接数。设为0表示无限制
redis.maxActive=600
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
redis.maxWait=1000
#在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;
redis.testOnBorrow=true

spring-redis.xml

<?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:cache="http://www.springframework.org/schema/cache"
       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
       http://www.springframework.org/schema/cache
       http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">

        <!-- 配置文件加载 -->
        <context:property-placeholder ignore-unresolvable="true" location="classpath:redis.properties"/>

        <cache:annotation-driven cache-manager="cacheManager"/>

        <!-- jedis 配置 -->
        <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
            <property name="maxIdle" value="${redis.maxIdle}" />
            <property name="minIdle" value="${redis.minIdle}" />
            <property name="maxWaitMillis" value="${redis.maxWait}" />
            <property name="testOnBorrow" value="${redis.testOnBorrow}" />
        </bean>
        <!-- redis服务器中心 -->
         <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
             <property name="poolConfig" ref="poolConfig" />
            <property name="port" value="${redis.port}" />
            <property name="hostName" value="${redis.host}" />
            <property name="password" value="${redis.password}" />
            <property name="timeout" value="-1"/>
         </bean>
         <!-- redisTemplate配置,redisTemplate是对Jedis的对redis操作的扩展,有更多的操作,封装使操作更便捷 -->
        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
            <property name="connectionFactory" ref="jedisConnectionFactory" />
            <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="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
            <property name="caches">
                <set>
                    <!-- 这里可以配置多个redis -->
                    <bean class="util.RedisCache">
                        <property name="redisTemplate" ref="redisTemplate" />
                        <property name="name" value="content"/>
                        <!-- name对应的名称要在类或方法的注解中使用 -->
                    </bean>
                </set>
            </property>
        </bean>

</beans>

JedisUtil

@Component
public class JedisUtil {
    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;
 
    private JedisConnection getJedis(){
        return jedisConnectionFactory.getConnection();
    }
 
    public byte[] set(byte[] key, byte[] value) {
        JedisConnection jedis = getJedis();
        try {
            jedis.set(key,value);
            return value;
        } finally {
            jedis.close();
        }
    }
 
    public void expire(byte[] key, int i) {
        JedisConnection jedis = getJedis();
        try {
            jedis.expire(key,i);
        } finally {
            jedis.close();
        }
    }
 
    public byte[] get(byte[] key) {
        JedisConnection jedis = getJedis();
        try {
            return jedis.get(key);
        } finally {
            jedis.close();
        }
    }
 
    public void del(byte[] key) {
        JedisConnection jedis = getJedis();
        try {
            jedis.del(key);
        } finally {
            jedis.close();
        }
    }
 
    public Set<byte[]> keys(String shiro_session_prefix) {
        JedisConnection jedis = getJedis();
        try {
            return jedis.keys((shiro_session_prefix + "*").getBytes());
        } finally {
            jedis.close();
        }
    }
}

RedisSessionDao

public class RedisSessionDao extends AbstractSessionDAO {

    @Autowired
    private JedisUtil jedisUtil;

    private final String shiro_session_prefix = "shiro-session:";

    private byte[] getKey(String key){
        return (shiro_session_prefix + key).getBytes();
    }

    private void saveSession(Session session){
        if(session != null && session.getId()!=null){
            byte[] key = getKey(session.getId().toString());
            byte[] value = SerializationUtils.serialize(session);
            jedisUtil.set(key,value);
            jedisUtil.expire(key,600);
        }
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionID = generateSessionId(session);
        assignSessionId(session,sessionID);
        saveSession(session);
        return sessionID;
    }

    @Override
    protected Session doReadSession(Serializable sessionID) {
        if(sessionID == null){
            return null;
        }
        byte[] key = getKey(sessionID.toString());
        byte[] value = jedisUtil.get(key);
        return (Session)SerializationUtils.deserialize(value);
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        saveSession(session);
    }

    @Override
    public void delete(Session session) {
        if(session == null && session.getId() != null){
            return;
        }
        byte[] key = getKey(session.getId().toString());
        jedisUtil.del(key);

    }

    @Override
    public Collection<Session> getActiveSessions() {
        Set<byte[]> keys = jedisUtil.keys(shiro_session_prefix);
        Set<Session> sessions = new HashSet<>();
        if(CollectionUtils.isEmpty(keys)){
            return sessions;
        }
        for(byte[] key:keys){
            Session session = (Session)SerializationUtils.deserialize(jedisUtil.get(key));
            sessions.add(session);
        }
        return sessions;
    }
}

CustomSessionManager

public class CustomSessionManager extends DefaultWebSessionManager {
    @Override
    protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
        Serializable sessionId = getSessionId(sessionKey);
        ServletRequest request = null;
        if (sessionKey instanceof WebSessionKey) {
            request = ((WebSessionKey)sessionKey).getServletRequest();
        }
        if(request != null && sessionId != null){
            Session session = (Session)request.getAttribute(sessionId.toString());
            if(session != null){
                return session;
            }
        }
        Session session = super.retrieveSession(sessionKey);
        if(request != null && sessionId != null){
            request.setAttribute(sessionId.toString(),session);
        }
        return session;
    }
}

spring-shiro.xml

    <!-- redisSessionDao -->
<bean id="redisSessionDao" class="com.xinjianqiao.mian.session.RedisSessionDao"/>

    <!-- Session Manager -->
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.CustomSessionManager">
        <property name="sessionDAO" ref="redisSessionDao"/>
</bean>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值