一步一步教你用shiro——4配置并自定义sessionDao

  • 一步一步教你用shiro——1引入shiro框架
  • 一步一步教你用shiro——2配置并自定义realm
  • 一步一步教你用shiro——3配置并自定义sessionManager
  • 一步一步教你用shiro——4配置并自定义sessionDao
  • 一步一步教你用shiro——5配置rememberMe
  • 一步一步教你用shiro——6总结和心得
public class MyRedisSessionDao extends AbstractSessionDAO{
    //redis中session过期时间
    private static final int SESSION_EXPIRE = 60 * 30;
    @Resource
    private RedisClient client;


    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session,sessionId);
        byte[] keyByte = RedisKey.getKeyByte(RedisKey.SESSION_PRE, sessionId.toString());
        byte[] sessionByte = SerializationUtils.serialize(session);
        client.setEx(keyByte, sessionByte, SESSION_EXPIRE);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        if (sessionId == null) {
            return null;
        }
        byte[] keyByte = RedisKey.getKeyByte(RedisKey.SESSION_PRE, sessionId.toString());
        byte[] sessionByte = client.get(keyByte);
        return (Session) SerializationUtils.deserialize(sessionByte);
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        byte[] keyByte = RedisKey.getKeyByte(RedisKey.SESSION_PRE, session.getId().toString());
        byte[] sessionByte = SerializationUtils.serialize(session);
        client.setEx(keyByte, sessionByte, SESSION_EXPIRE);
    }

    @Override
    public void delete(Session session) {
        byte[] keyByte = RedisKey.getKeyByte(RedisKey.SESSION_PRE, session.getId().toString());
        client.delete(keyByte);
    }

    @Override
    public Collection getActiveSessions() {
        Set keyByteSet = client.keys((RedisKey.SESSION_PRE + "*").getBytes());
        Set sessionSet = Sets.newHashSet();
        for (byte[] keyByte : keyByteSet) {
            byte[] sessionByte = client.get(keyByte);
            Session session = (Session) SerializationUtils.deserialize(sessionByte);
            if (session != null) {
                sessionSet.add(session);
            }
        }
        return sessionSet;
    }
}

你可能感兴趣的:(一步一步教你用shiro——4配置并自定义sessionDao)