Created
December 24, 2020 14:17
-
-
Save Honatas/e64d59a015f28f7bab01686055072d64 to your computer and use it in GitHub Desktop.
Redis Session Manager for Microservices. Check RedisClient: https://gist.github.com/Honatas/097a5dff24b99b688d40e433ebfae2bb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import org.apache.catalina.util.StandardSessionIdGenerator; | |
import redis.clients.jedis.Jedis; | |
public class SessionManager { | |
private static final String SESSION_TIMEOUT_KEY = "session.timeout"; | |
private static final String SESSION_TIMEOUT_DEFAULT = "1800"; // 30 minutes | |
private static StandardSessionIdGenerator gen = new StandardSessionIdGenerator(); | |
/** | |
* Creates a new session | |
*/ | |
public static String create(String sessionData) { | |
String sessionId = gen.generateSessionId(); | |
SessionManager.update(sessionId, sessionData); | |
return sessionId; | |
} | |
/** | |
* Updates the session | |
*/ | |
public static void update(String sessionId, String sessionData) { | |
try (Jedis jedis = RedisClient.getConnection()) { | |
jedis.set(sessionId, sessionData); | |
jedis.expire(sessionId, getSessionTimeout()); | |
} | |
} | |
/** | |
* Retrieves session data | |
*/ | |
public static String get(String sessionId) throws IOException { | |
try (Jedis jedis = RedisClient.getConnection()) { | |
String sessionData = jedis.get(sessionId); | |
if (sessionData != null) { | |
jedis.expire(sessionId, getSessionTimeout()); | |
} | |
return sessionData; | |
} | |
} | |
/** | |
* Refreshes session timeout | |
*/ | |
public static void refresh(String sessionId) throws IOException { | |
try (Jedis jedis = RedisClient.getConnection()) { | |
jedis.expire(sessionId, getSessionTimeout()); | |
} | |
} | |
/** | |
* Removes the session | |
*/ | |
public static void remove(String sessionId) { | |
try (Jedis jedis = RedisClient.getConnection()) { | |
jedis.del(sessionId); | |
} | |
} | |
/** | |
* Sets session timeout | |
*/ | |
public static void setSessionTimeout(Integer timeout) { | |
try (Jedis jedis = RedisClient.getConnection()) { | |
jedis.set(SESSION_TIMEOUT_KEY, timeout == null ? SESSION_TIMEOUT_DEFAULT : timeout.toString()); | |
} | |
} | |
/** | |
* Retrieves session timeout (in seconds). If not set, sets a default value. | |
*/ | |
private static Integer getSessionTimeout() { | |
try (Jedis jedis = RedisClient.getConnection()) { | |
String timeout = jedis.get(SESSION_TIMEOUT_KEY); | |
if (timeout == null) { | |
timeout = SESSION_TIMEOUT_DEFAULT; | |
jedis.set(SESSION_TIMEOUT_KEY, timeout); | |
} | |
return Integer.valueOf(timeout); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment