shiro redis session 共享
程序员文章站
2022-07-05 12:55:04
...
自定义SessionDao 继承 AbstractSessionDAO 重写方法
SerializableKit JedisKit 来自jfinal
package com.wahaha.haha.config;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collection;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import com.jfinal.ext.kit.SerializableKit;
import com.jfinal.ext.plugin.redis.JedisKit;
public class RedisSessionDao extends AbstractSessionDAO {
// 把session对象转化为byte保存到redis中
public byte[] sessionToByte(Session session) {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] bytes = null;
try {
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(session);
bytes = bo.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
// 把byte还原为session
public Session byteToSession(byte[] bytes) {
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
ObjectInputStream in;
SimpleSession session = null;
try {
in = new ObjectInputStream(bi);
session = (SimpleSession) in.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return session;
}
@Override
public void update(Session session) throws UnknownSessionException {
Serializable s = SerializableKit.toObject(sessionToByte(session));
JedisKit.set(session.getId().toString(), s);
}
@Override
public void delete(Session session) {
if (session == null || session.getId() == null) {
return;
}
JedisKit.del(session.getId().toString());
}
@Override
public Collection<Session> getActiveSessions() {
// TODO Auto-generated method stub
return null;
}
@Override
protected Serializable doCreate(Session session) {
Serializable sessionId = this.generateSessionId(session);
this.assignSessionId(session, sessionId);
Serializable s = SerializableKit.toObject(sessionToByte(session));
JedisKit.set(sessionId.toString(), s);
return sessionId;
}
@Override
protected Session doReadSession(Serializable sessionId) {
if (sessionId == null) {
return null;
}
try {
if (JedisKit.get(sessionId.toString()) == null) {
return null;
}
return byteToSession(SerializableKit.toByteArray(JedisKit.get(sessionId.toString())));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
上一篇: leetcode91. 解码方法
下一篇: 共享对象
推荐阅读