Over a million developers have joined DZone.

3 Ways to Use Redis Hash in Java

Check out this comparison of Jedis, Spring Data Redis, and Redisson to see how each library talks to Redis and interacts with hashes.

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

Needless to say, Map is vital and the most popular structure in Java. Redis has offered a data structure that closely resembles Java's Map structure, which has attracted a lot of interest from Java developers. There has been a growing number of Java libraries that talk to Redis, most of which have provided a way to interact with Redis Hashes. Let's compare three different ways of interacting with Redis Hahs in Java through examples of using three most popular Redis Java clients. In order to make them easy to understand and fairly comparable, each example uses the same popular binary codec, Kryo, to provide serialization/deserialization of the dummy data.

1. Jedis

Jedis only works with raw binary data so encoding/decoding logic are required each time when a Redis command is invoked. A Jedis instance also needs to be acquired each time from the instance pool before any command can be invoked.

private static byte[] encode(Kryo kryo, Object obj) {
    ByteArrayOutputStream objStream = new ByteArrayOutputStream();
    Output objOutput = new Output(objStream);
    kryo.writeClassAndObject(objOutput, obj);
    objOutput.close();
    return objStream.toByteArray();
}

private static <T> T decode(Kryo kryo, byte[] bytes) {
   return (T) kryo.readClassAndObject(new Input(bytes));
}

public static void main(String[] args) {
    JedisPool jedisPool = new JedisPool("127.0.0.1", 6379);

    Kryo kryo = new Kryo();
    kryo.register(MyKey.class);
    kryo.register(MyValue.class);

    Jedis jedis = jedisPool.getResource();

    MyKey key = new MyKey("Jhon", "+138129129113");
    byte[] keyArray = encode(kryo, key);

    MyValue value = new MyValue("Kremlin street", "Moscow");
    byte[] valueArray = encode(kryo, value);

    byte[] name = "myMap".getBytes();

    // put
    jedis.hset(name, keyArray, valueArray);

    // get
    byte[] mappedValueArray = jedis.hget(name, keyArray);
    MyValue mappedValue = decode(kryo, mappedValueArray);

    MyValue newValue = new MyValue("Kremlin street", "Moscow");
    byte[] newValueArray = encode(kryo, newValue);

    // putIfAbsent
    jedis.hsetnx(name, keyArray, newValueArray);

    jedis.close();
    jedisPool.close();
}

2. Spring Data Redis

Spring Data Redis allows you to implement your own data serializer through the RedisSerializer interface and use Jedis pools under the hood. So KryoSerializer needs to be implemented to in order to use the Kryo codec.

KryoSerializer Implementation

public static class KryoSerializer<T> implements RedisSerializer<T> {

    private Kryo kryo;

    public KryoSerializer(List<Class<?>> classes) {
        kryo = new Kryo();
        for (Class<?> clazz : classes) {
            kryo.register(clazz);
        }
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        ByteArrayOutputStream objStream = new ByteArrayOutputStream();
        Output objOutput = new Output(objStream);
        kryo.writeClassAndObject(objOutput, t);
        objOutput.close();
        return objStream.toByteArray();
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        return (T) kryo.readClassAndObject(new Input(bytes));
    }
}

Configuration

@Configuration
@ComponentScan
public static class Application {

    @Bean
    JedisConnectionFactory connectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setUsePool(true);
        return factory;
    }

    @Bean
    RedisTemplate<?, ?> redisTemplate(JedisConnectionFactory factory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setDefaultSerializer(new KryoSerializer<>(Arrays.asList(MyKey.class, MyValue.class)));
        template.setConnectionFactory(factory);
        return template;
    }

}

Usage Example

@Component
public static class MapBean {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void execute() {
        Kryo kryo = new Kryo();
        kryo.register(MyKey.class);
        kryo.register(MyValue.class);

        MyKey key = new MyKey("Jhon", "+138129129113");
        MyValue value = new MyValue("Pushkina street", "Moscow");
        HashOperations<String, MyKey, MyValue> hashOperations = redisTemplate.opsForHash();
        hashOperations.put("myKey", key, value);

        MyValue mappedValue = hashOperations.get("myKey", key);

        MyValue newValue = new MyValue("Tverskaya street", "Moscow");
        hashOperations.putIfAbsent("myKey", key, newValue);
    }

}

public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
    context.getBean(MapBean.class).execute();
    context.close();
}

3. Redisson

Redisson supports many popular codecs, including Kryo. It maintains the connection pool and topology update for clusters, master/slave, and single Redis servers. The Redisson API covers not only Redis hash operations but also fully implements java.util.Map and java.util.concurrent.ConcurrentMap interfaces. It also supports map entry eviction and local cache for map entires.

public static void main(String[] args) {
    Config config = new Config();
    config.setCodec(new KryoCodec(Arrays.asList(MyKey.class, MyValue.class)))
            .useSingleServer().setAddress("127.0.0.1:6379");

    RedissonClient redisson = Redisson.create(config);

    RMap<MyKey, MyValue> map = redisson.getMap("myMap");
    MyKey key = new MyKey("Jhon", "+138129129113");
    MyValue value = new MyValue("Kremlin street", "Moscow");
    map.put(key, value);

    MyValue mappedValue = map.get(key);

    MyValue newValue = new MyValue("Tverskaya street", "Moscow");
    map.fastPutIfAbsent(key, newValue);

    redisson.shutdown();
}

Conclusion

It is bluntly obvious that in terms of code simplicity, Redisson is a much better choice than other Redis Java clients when working with Redis Hashes. Or any other Redis structures for the same purpose, as a matter of fact, but that's for another post.

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:
redis ,java ,hash ,hashmap

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}