Created
July 12, 2015 15:20
-
-
Save mp911de/a00924f74378c4af3995 to your computer and use it in GitHub Desktop.
Example for loading/storing a string-based HttpSession from/to Redis using CDI
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
package biz.paluch.redis.example; | |
import java.util.Enumeration; | |
import java.util.Map; | |
import javax.annotation.PostConstruct; | |
import javax.annotation.PreDestroy; | |
import javax.inject.Inject; | |
import javax.servlet.http.HttpSession; | |
import com.lambdaworks.redis.RedisClient; | |
import com.lambdaworks.redis.RedisConnection; | |
/** | |
* @author <a href="mailto:mpaluch@paluch.biz">Mark Paluch</a> | |
*/ | |
public class RedisExample { | |
@Inject | |
private RedisClient redisClient; | |
private RedisConnection<String, String> connection; | |
public void storeSessionInRedis(HttpSession session) { | |
Enumeration<String> names = session.getAttributeNames(); | |
while (names.hasMoreElements()) { | |
String attributeName = names.nextElement(); | |
connection.hset(session.getId(), attributeName, session.getAttribute(attributeName).toString()); | |
} | |
} | |
public void loadSessionFromRedis(HttpSession session) { | |
Map<String, String> sessionAttributes = connection.hgetall(session.getId()); | |
for (Map.Entry<String, String> entry : sessionAttributes.entrySet()) { | |
session.setAttribute(entry.getKey(), entry.getValue()); | |
} | |
} | |
@PostConstruct | |
public void postConstruct() { | |
connection = redisClient.connect(); | |
} | |
@PreDestroy | |
public void preDestroy() { | |
connection.close(); | |
} | |
} |
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
package biz.paluch.redis.example; | |
import javax.enterprise.inject.Produces; | |
import com.lambdaworks.redis.RedisURI; | |
/** | |
* @author <a href="mailto:mpaluch@paluch.biz">Mark Paluch</a> | |
*/ | |
public class RedisURIProducer { | |
@Produces | |
public RedisURI getRedisURI() { | |
return RedisURI.create("redis://password@localhost:6379/0"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment