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.
In this lesson, you will learn how to:
- Connect to a Redis server using Java.
- Verify your connection by storing and retrieving a value.
Here’s the simple code you’ll be working with:
Let's break down the code:
- We import classes from the Lettuce API to provide the Java interface to Redis.
- We create a
RedisClientobject to establish a connection to the Redis server running onlocalhostat port6379and database0— 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> syncCommandsto execute commands. - We set a key-value pair in Redis using the
setmethod, where the key is"name"and the value is"Redis Learner". - We retrieve the value stored in Redis using the
getmethod and print it to the console. - The
catchblock handles any connection exceptions, providing a user-friendly message in case of connection failure. - Finally, resource cleanup is ensured by shutting down the
RedisClientin thefinallyblock.
