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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Boosting Application Performance With MicroStream and Redis Integration
  • Redis-Based Tomcat Session Management
  • Multi-Tenancy Implementation Using Spring Boot, MongoDB, and Redis
  • Learning Redis Basic Data Structure and Mapping With Java Data Structure

Trending

  • How to Build Real-Time BI Systems: Architecture, Code, and Best Practices
  • AI-Driven Root Cause Analysis in SRE: Enhancing Incident Resolution
  • Cloud Security and Privacy: Best Practices to Mitigate the Risks
  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  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 user avatar
Nikita Koksharov
·
Oct. 06, 16 · Opinion
Likes (9)
Comment
Save
Tweet
Share
98.0K Views

Join the DZone community and get the full member experience.

Join For Free

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
  • Multi-Tenancy Implementation Using Spring Boot, MongoDB, and Redis
  • Learning Redis Basic Data Structure and Mapping With Java Data Structure

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!