Learnitweb

Storing and Retrieving Java Objects in Redis

So far, we have learned how to store and retrieve simple key-value pairs (strings) in Redis using Redisson. In this tutorial, we’ll go one step further and explore how to store entire Java objects in Redis.
This is an essential concept because, in real-world applications, we often work with structured data — not just plain strings.


1. Why Store Java Objects in Redis?

Redis can act as an in-memory cache, message broker, or even a lightweight database. Often, you’ll need to cache entire Java objects such as user profiles, product information, or configurations — not just primitive strings.

Redisson provides an elegant API to serialize and store complex objects with minimal effort.


2. Creating a Student Class

Let’s begin by creating a simple Java class that we’ll store in Redis.

package com.example.redis.model;

import java.util.List;

public class Student {
    private String name;
    private int id;
    private String city;
    private List<Integer> marks;

    // Default constructor
    public Student() {}

    // Parameterized constructor
    public Student(int id, String name, String city, List<Integer> marks) {
        this.id = id;
        this.name = name;
        this.city = city;
        this.marks = marks;
    }

    // Getters and Setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public String getCity() { return city; }
    public void setCity(String city) { this.city = city; }

    public List<Integer> getMarks() { return marks; }
    public void setMarks(List<Integer> marks) { this.marks = marks; }

    @Override
    public String toString() {
        return "Student{id=" + id + ", name='" + name + "', city='" + city + "', marks=" + marks + "}";
    }
}

This class represents a student with fields such as id, name, city, and a list of marks.
We’ll use this class to demonstrate how to persist and retrieve Java objects in Redis.


3. Storing a Java Object in Redis

Now let’s write a test that stores a Student object in Redis.

@Test
public void storeJavaObjectTest() {
    Student student = new Student(10, "Marshall", "Atlanta", Arrays.asList(90, 85, 78));

    RBucket<Student> bucket = redisson.getBucket("student:1");
    bucket.set(student);

    System.out.println("Stored student: " + student);
}

When this code runs, Redisson serializes the Student object and stores it in Redis under the key student:1.

If you check Redis CLI after running the test:

127.0.0.1:6379> KEYS *
1) "student:1"

When you attempt to GET the key:

127.0.0.1:6379> GET student:1

You’ll notice that the value appears as binary or unreadable characters.
That’s because Redisson uses JDK serialization (JSerializationCodec) by default. The data is stored in a binary format optimized for speed, not human readability.


4. Fixing the Serialization Issue

If you try the above code and face a serialization error like:

java.io.NotSerializableException: com.example.redis.model.Student

That’s because the default codec expects the object to implement java.io.Serializable.
You can fix it by updating your Student class:

public class Student implements Serializable {
    private static final long serialVersionUID = 1L;
    ...
}

Now, Redisson will serialize and store the object successfully.


5. Using JSON Serialization for Readability

The default binary serialization works well but makes it difficult to inspect stored data in Redis.
For better visibility, we can use JSON-based serialization by providing a JSON codec.

Redisson supports various codecs like:

  • StringCodec
  • JsonJacksonCodec
  • JsonTypedJsonCodec
  • Kryo5Codec
  • AvroCodec
  • MessagePackCodec
  • ProtocolBuffersCodec

Let’s use the Jackson JSON Codec, which serializes objects into JSON strings.

@Test
public void storeObjectAsJsonTest() {
    Student student = new Student(10, "Marshall", "Atlanta", Arrays.asList(90, 85, 78));

    RBucket<Student> bucket = redisson.getBucket("student:json:1", new JsonJacksonCodec());
    bucket.set(student);

    Student retrieved = bucket.get();
    System.out.println("Retrieved student: " + retrieved);
}

Now, if you inspect the key in Redis CLI:

127.0.0.1:6379> GET student:json:1

You’ll see a clean JSON structure:

{
  "@class": "com.example.redis.model.Student",
  "id": 10,
  "name": "Marshall",
  "city": "Atlanta",
  "marks": [90, 85, 78]
}

6. Removing Class Metadata

By default, Jackson stores the fully qualified class name (@class) in JSON to help with deserialization.
However, this can cause problems if your class name or package structure changes later (for example, renaming Student to Person).

To prevent this, you can use JsonTypedJsonCodec, which omits class metadata:

RBucket<Student> bucket = redisson.getBucket("student:json:typed", new TypedJsonJacksonCodec(Student.class));

Now, Redis will store only the object fields in JSON format:

{
  "id": 10,
  "name": "Marshall",
  "city": "Atlanta",
  "marks": [90, 85, 78]
}

This structure is cleaner, portable, and safer for long-term storage.


7. Comparing Binary vs JSON Storage

AspectBinary (Default)JSON (Using JsonJacksonCodec)
ReadabilityNot human-readableFully readable
PerformanceFaster serializationSlightly slower
Storage SizeSmallerSlightly larger
PortabilityClass-dependentLanguage-agnostic
Use CaseInternal caching, performance-critical dataShared data, debugging, readable cache

In most application use cases, binary serialization is preferred for performance.
However, when debugging or integrating with multiple systems, JSON is more practical.


8. Adding Lists and Nested Objects

Redis via Redisson handles nested objects and collections automatically when using JSON serialization.

For example, our Student object already contains a List<Integer> named marks.
We can easily store and retrieve this object:

@Test
public void storeObjectWithListTest() {
    Student student = new Student(10, "Marshall", "Atlanta", Arrays.asList(90, 85, 78));

    RBucket<Student> bucket = redisson.getBucket("student:withlist", new JsonJacksonCodec());
    bucket.set(student);

    System.out.println("Stored student with marks successfully!");
}

Now, if you view this key in Redis, you’ll see:

{
  "@class": "com.example.redis.model.Student",
  "id": 10,
  "name": "Marshall",
  "city": "Atlanta",
  "marks": [90, 85, 78]
}

The list is stored and retrieved seamlessly.


9. Summary

In this tutorial, we covered:

  1. How to store and retrieve Java objects in Redis using Redisson.
  2. How to resolve serialization issues by implementing Serializable.
  3. How to use JSON serialization (Jackson) for human-readable data.
  4. How to remove class metadata for cleaner and more portable JSON storage.
  5. How Redis handles nested objects and lists using Redisson codecs.