How to Connect to Redis Sentinel in Java

Redis is an in-memory data structure store with a wide range of use cases: NoSQL databases, caches, message brokers, and more. Redis Sentinel is a high-availability version of Redis that uses a distributed master/slave architecture and can automatically perform monitoring and alerting for your Redis deployment.

Whether you're using Redis or Redis Sentinel, you need to establish a connection to the Redis server to begin storing and retrieving data. However, neither Redis nor Redis Sentinel can work with the Java programming language out of the box. Instead, Java developers who want to take advantage of Redis should install a third-party Redis Java library such as Redisson.

Redisson is a Redis Java client that makes it as easy as possible for Java developers to work with Redis. Many familiar Java data structures, services, and components are available in the Redisson framework, making them available within Redis so that programmers can start using Redis using the Java constructs they already know.

To make a connection to Redis Sentinel in Java using Redisson, follow the steps below.

Step 0: Run a Redis Sentinel Server

Before you get started using Java with Redis Sentinel, you'll need to create a Redis Sentinel server. Follow this guide from Bitnami to get Redis Sentinel up and running.

Step 1: Add the Redisson Dependency to Your Project Files

The next step is to add the Redisson dependency to the build automation tool in your Java project, such as Maven or Gradle. If you're using Maven, add the following code block to your pom.xml file:


If you're using Gradle, add the following line to your build.gradle file:

compile 'org.redisson:redisson:3.28.0'

Step 2: Create the Configuration and Connect

Next, create a Redisson configuration for Redis Sentinel in your Java code using the Config object. Insert the lines below:

    Config config = new Config();

You can also use "rediss" instead of "redis" to establish an SSL connection.

Below are three ways of establishing a connection to Redis Sentinel in Java, depending on what kind of Redisson client you want to use: the sync/async API, the reactive API, and the RxJava3 API, respectively.

    RedissonClient redisson = Redisson.create(config);
    RedissonReactiveClient redissonReactive = redisson.reactive();
    RedissonRxClient redissonRx = redisson.rxJava();

Step 3: Interact with Redis in Java

You can now start working with Redis Sentinel in Java using the Redisson framework. For example, the code below illustrates how to use the RMap interface in Redisson, which is a Redis version of the Map interface in Java:

    RMap map = redisson.getMap("simple");
    map.put(1, 0);
    map.put(3, 5);
    map.put(4, 6);
    map.put(7, 8);

To learn more about connecting to Redis Sentinel in Java with Redisson, check out the Redisson documentation on GitHub today.

Similar articles