ru.zinin.redis.session.RedisSessionTemplate Maven / Gradle / Ivy
package ru.zinin.redis.session;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import javax.servlet.ServletContext;
import java.util.HashSet;
import java.util.Set;
/**
* Date: 12.11.11 12:08
*
* @author Alexander V. Zinin ([email protected])
*/
public class RedisSessionTemplate {
private JedisPool jedisPool;
private ServletContext servletContext;
private boolean disableListeners = false;
public RedisSessionTemplate() {
}
public RedisSessionTemplate(JedisPool jedisPool, ServletContext servletContext) {
this.jedisPool = jedisPool;
this.servletContext = servletContext;
}
public JedisPool getJedisPool() {
return jedisPool;
}
public void setJedisPool(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}
public ServletContext getServletContext() {
return servletContext;
}
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
public boolean isDisableListeners() {
return disableListeners;
}
public void setDisableListeners(boolean disableListeners) {
this.disableListeners = disableListeners;
}
private void verifyInitialization() {
if (jedisPool == null) {
throw new IllegalStateException("JedisPool is not initialized");
}
if (servletContext == null) {
throw new IllegalStateException("ServletContext is not initialized");
}
}
public Set getAllSessions() {
verifyInitialization();
Set sessionIds;
Jedis jedis = jedisPool.getResource();
try {
sessionIds = jedis.zrangeByScore(RedisSessionKeys.getSessionsKey(), 0, Double.MAX_VALUE);
jedisPool.returnResource(jedis);
} catch (Throwable e) {
jedisPool.returnBrokenResource(jedis);
throw new RuntimeException(e);
}
Set result = new HashSet(sessionIds.size());
for (String sessionId : sessionIds) {
RedisHttpSession session = new RedisHttpSession(sessionId, jedisPool, servletContext, disableListeners);
if (session.isValid()) {
result.add(session);
}
}
return result;
}
public RedisHttpSession getSession(String id) {
verifyInitialization();
return new RedisHttpSession(id, jedisPool, servletContext, disableListeners);
}
}