Redis - Java
Redis 与现代 Java
Section titled “Redis 与现代 Java”要在现代 Java 应用程序中使用 Redis,你应该使用像 Maven 或 Gradle 这样的依赖管理工具来处理 Redis 客户端库。最流行的客户端是 Jedis,但像 Lettuce 这样的其他客户端也是优秀的选择,特别是对于异步和响应式应用程序。本指南将重点介绍 Jedis。
1. 项目设置(Maven 或 Gradle)
Section titled “1. 项目设置(Maven 或 Gradle)”告别手动下载 JAR 包。将 Jedis 依赖添加到你的项目构建文件中。
Maven (pom.xml)
Section titled “Maven (pom.xml)”<dependencies> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>5.1.0</version> <!-- 检查最新版本 --> </dependency></dependencies>Gradle (build.gradle.kts)
Section titled “Gradle (build.gradle.kts)”dependencies { implementation("redis.clients:jedis:5.1.0") // 检查最新版本}2. 最佳实践:使用连接池
Section titled “2. 最佳实践:使用连接池”为每个 Redis 命令创建新连接是低效且缓慢的。在实际应用程序中,你应该使用连接池(Connection Pool),例如 JedisPool,来管理和复用连接。它是线程安全的,应该只创建一次并在整个应用程序中共享。
import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;import redis.clients.jedis.exceptions.JedisException;
public class RedisConnector { // 创建连接池的单例实例 private static final JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), "localhost", 6379);
public static void main(String[] args) { // 从连接池获取资源,并使用 try-with-resources 确保其被返回 try (Jedis jedis = jedisPool.getResource()) { // 检查连接 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(); }
// 记得在应用程序关闭时关闭连接池 jedisPool.close(); }}编译并运行此代码。你的 IDE 或构建工具将为你处理依赖项。输出应为:
Connection to server successful.Server is running: PONG3. 代码示例
Section titled “3. 代码示例”以下所有示例都假设你已配置 JedisPool 并使用 try-with-resources 模式进行安全的连接处理。
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());}import java.util.List;
// ... 在使用 JedisPool 的方法内部try (Jedis jedis = jedisPool.getResource()) { String listKey = "tech-stack";
// 在运行示例前清除旧的列表项 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());}键示例(使用 SCAN)
Section titled “键示例(使用 SCAN)”警告: 切勿在生产环境中使用 KEYS * 命令。它是一个阻塞操作,在扫描所有键时可能会导致 Redis 服务器冻结。安全且推荐的替代方案是 SCAN。
import redis.clients.jedis.params.ScanParams;import redis.clients.jedis.resps.ScanResult;import java.util.ArrayList;import java.util.List;
// ... 在使用 JedisPool 的方法内部try (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());}对于企业级应用程序,可以考虑使用像 Spring Data Redis 这样的框架抽象层,它简化了连接管理、对象映射,并提供了模板类以实现更简单的 Redis 交互。