How to Get Data From Redis in Java

Redis is an in-memory data structure store that is commonly used to implement NoSQL databases, caches, and message brokers. Naturally, it's essential for Redis developers to be able to not only store data, but also efficiently retrieve it.

Unfortunately, Redis isn't designed to work with programming languages such as Java out of the box. Instead, Java developers who want to work with Redis can use a third-party Redis Java library such as Redisson.

What is Redisson?

Redisson is a Redis Java client that makes it easier for Java developers to get started using Redis. The Redisson framework has dozens of implementations of familiar Java data structures, services, and components. This makes it easy for Java programmers to work with Redis using the Java constructs they've become accustomed to.

As an example, the RBucket interface in Redisson is used to store any kind of object (with a maximum size of 512 megabytes). Each instance of an RBucket has its own name, which can later be used to retrieve the data inside it.

Another example is the RMap interface in Redisson, which should be familiar to any Java developers who have used the Map interface. Like the default Java Map, an RMap is an association between keys and values in which each key maps to a maximum of one value. This makes it ideal for use cases that require a quick lookup operation (for example, finding a person's name based on their telephone number).

Getting Data from Redis in Java with Redisson

Below is a simple demonstration of how to get data from Redis in Java using the Redisson framework. After establishing a connection to the Redisson client, we proceed as follows:

  • In the first block of code, we retrieve the relevant RBucket from the Redisson client using the bucket's name and the getBucket() operation; we can then print out the value inside it using bucket.get().
  • In the second block of code, we retrieve the relevant RMap from the Redisson client using the map's name and the getMap() operation. We can then fetch and print a specific value from the RMap by providing the key associated with that value.
import org.redisson.api.RedissonClient;
import org.redisson.Redisson;
import org.redisson.api.RBucket;
import org.redisson.api.RMap;

public class Main {
  public static void main(String[] args) {
    RedissonClient redisson = Redisson.create();

    String key = "mykey";
    RBucket bucket = redisson.getBucket(key);
    String value = bucket.get();
    System.out.println("value: " + value);

    String hashName = "myHash";
    RMap map = redisson.getMap(hashName);
    key = "myKey";
    value = map.get(key);
    System.out.println("value: " + value);

To learn more about the many options for working with Redis data in Java using the Redisson library, check out the Redisson documentation on GitHub.

Similar articles