DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Boosting Application Performance With MicroStream and Redis Integration
  • Redis-Based Tomcat Session Management
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop

Trending

  • Genkit Flows as senro Steps: Extremely Powerful AI Pipelines in Go
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • PWA on iOS, Part 2: HTTPS, Manifest and Service Worker
  • PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They Look

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. 3 Ways to Use Redis Hash in Java

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.

By 
Nikita Koksharov
·
Oct. 06, 16 · Opinion
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
98.9K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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 Hash in Java through examples of using three most popular Redis Java clients - Jedis, Spring Data Redis and Redisson. 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("Broad street", "New York");
    map.put(key, value);

    MyValue mappedValue = map.get(key);

    MyValue newValue = new MyValue("Narrow street", "New York");
    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.

Redis (company) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Boosting Application Performance With MicroStream and Redis Integration
  • Redis-Based Tomcat Session Management
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook