Lettuce 指南 (Java)
将您的 Lettuce 应用连接到 Redis 数据库
Lettuce 是一个先进的 Java 客户端,支持同步、异步和响应式连接。如果您只需要同步连接,可能会发现另一个 Java 客户端 Jedis 更易于使用。
以下部分解释了如何安装 Lettuce
并将您的应用程序连接到 Redis 数据库。
Lettuce
需要运行中的 Redis 服务器。请参阅 此处 查看 Redis 开源版的安装说明。
安装
要在您的应用程序中包含 Lettuce 作为依赖项,请如下所示编辑相应的依赖文件。
如果您使用 Maven,请将以下依赖项添加到您的 pom.xml
中
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>6.3.2.RELEASE</version> <!-- Check for the latest version on Maven Central -->
</dependency>
如果您使用 Gradle,请将此行添加到您的 build.gradle
文件中
dependencies {
compileOnly 'io.lettuce:lettuce-core:6.3.2.RELEASE'
}
如果您希望直接使用 JAR 文件,请从 Maven Central 或任何其他 Maven 仓库下载最新的 Lettuce 以及可选的 Apache Commons Pool2 JAR 文件。
要从源代码构建,请参阅 Lettuce 源代码 GitHub 仓库上的说明。
连接和测试
使用以下代码连接到本地服务器。此示例还存储和检索一个简单的字符串值以测试连接。
import io.lettuce.core.*;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
public class ConnectBasicTest {
public void connectBasic() {
RedisURI uri = RedisURI.Builder
.redis("localhost", 6379)
.build();
RedisClient client = RedisClient.create(uri);
StatefulRedisConnection<String, String> connection = client.connect();
RedisCommands<String, String> commands = connection.sync();
commands.set("foo", "bar");
String result = commands.get("foo");
System.out.println(result); // >>> bar
connection.close();
client.shutdown();
}
}
更多信息
Lettuce 参考指南 提供了更多示例和 API 参考。您可能还对 Lettuce 使用的 Project Reactor 库感兴趣。
另请参阅本节中的其他页面以获取更多信息和示例