Using Redis Hash with Jedis

Redis Hashes are maps between string fields and string values, so they are the perfect data type to represent objects (eg: A User with a number of fields like name, surname, age, and so forth)

That is the definition we have on redis documentation.

So, lets start with a simple user class that could be seen below:

public class User {

     private String username;
     private String email;
     private String password;
     private String firstName;
     private String lastName;

Using Jedis we are able to store an object of this class in Redis, let’s see an example:

public void insertUser(User user){
     Map<String, String> userProperties = new HashMap<String, String>();
     userProperties.put("username", user.getUsername());
     userProperties.put("firstName", user.getFirstName());
     userProperties.put("lastName", user.getLastName());
     userProperties.put("email", user.getEmail());
     userProperties.put("password", user.getPassword());

     jedis.hmset("user:" + user.getUsername(), userProperties);

As we could see basically we need to create a map containing the fields for the hash, and then we could use the HMSET command that allow us to set more than one field on the set.

We can also set only one field on the hash using the command hset, follow an example:

public void updateEmail(User user){
    jedis.hset("user:" + user.getUsername(), "email", user.getEmail());

Now we need to retrieve the entire User object from the Redis Hash, we can use HMGET where we need to specify which fields we want to retrieve or we can use the HGETALL that returns all fields for the given key. Below we can see an example of HGETALL:

public User loadUser(String username){
    Map<String, String> properties = jedis.hgetAll("user:" + username);
    User user = new User();
    //fill all attributes

    return user;

To avoid the repeated code to create the bean from the Map and to create the bean from the map, we can use some libraries like commons Bean Utils that have some utility classes for doing that job.

We can see an example below:

//Getting the map of properties
properties = BeanUtilsBean.getInstance().describe(object);

//Populating the bean from the Map
BeanUtilsBean.getInstance().populate(bean, properties);

There are other commands that we can use with hashes, you can see all them on the redis page.

See you in the next post.