Skip to content

Instantly share code, notes, and snippets.

@mp911de
Created July 12, 2015 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mp911de/a00924f74378c4af3995 to your computer and use it in GitHub Desktop.
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
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();
}
}
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