0
0
Redisquery~5 mins

Redis with Java (Jedis, Lettuce)

Choose your learning style9 modes available
Introduction

Redis is a fast database that stores data in memory. Using Java libraries like Jedis or Lettuce helps Java programs talk to Redis easily.

You want to save and get data quickly in a Java app.
You need to cache data to make your app faster.
You want to share data between different parts of your Java program.
You want to use Redis features like counters or lists from Java.
You want a simple way to connect Java with Redis without writing complex code.
Syntax
Redis
Jedis jedis = new Jedis("localhost", 6379);
jedis.set("key", "value");
String value = jedis.get("key");
jedis.close();

Replace "localhost" and 6379 with your Redis server address and port if different.

Always close the connection after use to free resources.

Examples
Store and get a simple string value using Jedis.
Redis
Jedis jedis = new Jedis("localhost", 6379);
jedis.set("name", "Alice");
String name = jedis.get("name");
jedis.close();
Using Lettuce to set and get a value from Redis.
Redis
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

RedisClient client = RedisClient.create("redis://localhost:6379");
StatefulRedisConnection<String, String> connection = client.connect();
RedisCommands<String, String> commands = connection.sync();
commands.set("city", "Paris");
String city = commands.get("city");
connection.close();
client.shutdown();
Sample Program

This Java program connects to Redis using Jedis, stores the string "Java" with key "language", retrieves it, and prints it.

Redis
import redis.clients.jedis.Jedis;

public class RedisExample {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("localhost", 6379);
        jedis.set("language", "Java");
        String value = jedis.get("language");
        System.out.println("Stored value: " + value);
        jedis.close();
    }
}
OutputSuccess
Important Notes

Jedis is simple and easy for beginners.

Lettuce supports async and reactive programming styles.

Make sure Redis server is running before connecting.

Summary

Jedis and Lettuce are Java libraries to connect to Redis.

They let you store and get data from Redis easily.

Always close connections to avoid resource leaks.