Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a Map<String, String> to a Value type with Jedis

So, I have a value type :

class Session {
    long createdAt;
    List<String> postIds;
}

Using the jedis client(3.0.0-m1 is that matters), I am currently performing an hset to create the entries and hgetAll to retrieve all the key-values:

private redis.clients.jedis.Jedis jedis;

void createSession(String idAsKey, Map<String, String> hashFieldValues) {
    jedis.hset(idAsKey, hashFieldValues);
}


Map<String, String> fetchSession(String idAsKey) {
    return jedis.hgetAll(idAsKey);
}

The challenge that I am currently looking at is the ease of converting the Map<String, String> into the Session object. Is there an existing way to do this?

Server response for an equivalent command

1) "createdAt"
2) "1556099708307"
3) "postIds"
4) "[a, b, c]"

PS: Starting to learn Redis, hoping this kind of mapping might have already been solved for. Yes, not looking for a client change as an answer at least.

like image 882
Naman Avatar asked Sep 22 '26 20:09

Naman


2 Answers

Jedis doesn't offer a way to map objects to hash structures.

If you are using spring, then you can look at HashMappers. A HashMapper converts a POJO to a hash and vice-versa. In your case, the HashMapper will convert a Session to a hash, and the other way round.

like image 190
Sripathi Krishnan Avatar answered Sep 25 '26 14:09

Sripathi Krishnan


You are not using the fields separately, but simultaneously. Because of that, I'd suggest you to use plain and simple Redis Strings instead of using Redis Hashes. So you'd be using set to save entries and get to retrieve them.

Using above suggestions, your code may become as follows:

private redis.clients.jedis.Jedis jedis;
private com.google.gson.Gson gson; // see Note

void createSession(String idAsKey, Session object) {
    String serializedValue = gson.toJson(object);
    jedis.set(idAsKey, serializedValue);
}

Session fetchSession(String idAsKey) {
    String serializedValue = jedis.get(idAsKey);
    Session deserializedObject = gson.fromJson(serializedValue, Session.class);
    return deserializedObject;
}

Note: I have used Gson for the purpose of serialization/deserialization. Needless to say, you can use any library.

like image 28
sazzad Avatar answered Sep 25 '26 13:09

sazzad