Connecting to a Redis Server

Welcome to the first lesson of our Redis course! In this unit, we'll start with the very basics — connecting to a Redis server. Understanding how to establish this connection is essential since it forms the backbone of all the operations you'll perform with Redis. By the end of this lesson, you’ll be confident in setting up a connection to a Redis server and verifying that connection through simple operations.

What You'll Learn

In this lesson, you will learn how to:

  1. Connect to a Redis server using Java.
  2. Verify your connection by storing and retrieving a value.
Code Example with Explanation

Here’s the simple code you’ll be working with:

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisConnectionException;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

public class RedisConnectionExample {

    public static void main(String[] args) {
        // Connect to the Redis server
        RedisClient redisClient = RedisClient.create("redis://localhost:6379/0");
        try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
            // Obtain the synchronous commands API
            RedisCommands<String, String> syncCommands = connection.sync();

            // Verify the connection by setting and getting a value
            syncCommands.set("name", "Redis Learner");
            String value = syncCommands.get("name");

            System.out.println("Stored string in Redis: " + value);
        } catch (RedisConnectionException e) {
            System.out.println("Failed to connect to the Redis server. Please check the server status.");
        } finally {
            redisClient.shutdown();
        }
    }
}

Let's break down the code:

  • We import classes from the Lettuce API to provide the Java interface to Redis.
  • We create a RedisClient object to establish a connection to the Redis server running on localhost at port 6379 and database 0 — the default database.
  • Within a try-resource block, we open a connection using StatefulRedisConnection<String, String> to ensure that resources are closed even if the operation fails.
  • We obtain a synchronous commands API with RedisCommands<String, String> syncCommands to execute commands.
  • We set a key-value pair in Redis using the set method, where the key is "name" and the value is "Redis Learner".
  • We retrieve the value stored in Redis using the get method and print it to the console.
  • The catch block handles any connection exceptions, providing a user-friendly message in case of connection failure.
  • Finally, resource cleanup is ensured by shutting down the RedisClient in the finally block.
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal