Redis - Java
Redis with Modern Java
Section titled “Redis with Modern Java”To use Redis in a modern Java application, you should use a dependency manager like Maven or Gradle to handle the Redis client library. The most popular client is Jedis, but others like Lettuce are also excellent choices, especially for asynchronous and reactive applications. This guide will focus on Jedis.
1. Project Setup with Maven or Gradle
Section titled “1. Project Setup with Maven or Gradle”Forget manual JAR downloads. Add the Jedis dependency to your project’s build file.
Maven (pom.xml)
Section titled “Maven (pom.xml)”<dependencies> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>5.1.0</version> <!-- Check for the latest version --> </dependency></dependencies>Gradle (build.gradle.kts)
Section titled “Gradle (build.gradle.kts)”dependencies { implementation("redis.clients:jedis:5.1.0") // Check for the latest version}2. Best Practice: Using a Connection Pool
Section titled “2. Best Practice: Using a Connection Pool”Creating a new connection for every Redis command is inefficient and slow. In a real application, you should use a connection pool, like JedisPool, to manage and reuse connections. It’s thread-safe and should be created once and shared throughout your application.
import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;import redis.clients.jedis.exceptions.JedisException;
public class RedisConnector { // Create a singleton instance of the pool private static final JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), "localhost", 6379);
public static void main(String[] args) { // Get a resource from the pool and use try-with-resources to ensure it's returned try (Jedis jedis = jedisPool.getResource()) { // Check connection System.out.println("Connection to server successful."); System.out.println("Server is running: " + jedis.ping()); } catch (JedisException e) { System.err.println("Failed to connect to Redis: " + e.getMessage()); e.printStackTrace(); }
// Remember to close the pool when your application shuts down jedisPool.close(); }}Compile and run this code. Your IDE or build tool will handle the dependencies for you. The output should be:
Connection to server successful.Server is running: PONG3. Code Examples
Section titled “3. Code Examples”All examples below assume you have a JedisPool configured and use the try-with-resources pattern for safe connection handling.
String Example
Section titled “String Example”try (Jedis jedis = jedisPool.getResource()) { String key = "tutorial-name"; String value = "Modern Redis Tutorial";
jedis.set(key, value); System.out.println("Set key '" + key + "' to '" + value + "'");
String storedValue = jedis.get(key); System.out.println("Retrieved value: " + storedValue);} catch (JedisException e) { System.err.println("Redis operation failed: " + e.getMessage());}List Example
Section titled “List Example”import java.util.List;
// ... inside a method with a JedisPooltry (Jedis jedis = jedisPool.getResource()) { String listKey = "tech-stack";
// Clear old list items before running example jedis.del(listKey);
// Add items to the left of the list jedis.lpush(listKey, "Java", "Docker", "Redis");
// Get all items from the list List<String> stack = jedis.lrange(listKey, 0, -1); System.out.println("Current tech stack: " + stack);} catch (JedisException e) { System.err.println("Redis operation failed: " + e.getMessage());}Keys Example (Using SCAN)
Section titled “Keys Example (Using SCAN)”Warning: Never use the KEYS * command in a production environment. It is a blocking operation that can freeze your Redis server while it scans all keys. The safe and recommended alternative is SCAN.
import redis.clients.jedis.params.ScanParams;import redis.clients.jedis.resps.ScanResult;import java.util.ArrayList;import java.util.List;
// ... inside a method with a JedisPooltry (Jedis jedis = jedisPool.getResource()) { System.out.println("\nScanning for keys with pattern 'tutorial-*: '"); ScanParams scanParams = new ScanParams().match("tutorial-*").count(100); String cursor = ScanParams.SCAN_POINTER_START; List<String> matchingKeys = new ArrayList<>();
do { ScanResult<String> scanResult = jedis.scan(cursor, scanParams); matchingKeys.addAll(scanResult.getResult()); cursor = scanResult.getCursor(); } while (!cursor.equals(ScanParams.SCAN_POINTER_START));
if (matchingKeys.isEmpty()) { System.out.println("No matching keys found."); } else { System.out.println("Found keys: " + matchingKeys); }} catch (JedisException e) { System.err.println("Redis operation failed: " + e.getMessage());}Further Learning
Section titled “Further Learning”For enterprise applications, consider using a framework abstraction like Spring Data Redis, which simplifies connection management, object mapping, and provides template classes for easier Redis interaction.