Jedis 指南 (Java)
将 Java 应用程序连接到 Redis 数据库
Jedis 是 Redis 的同步 Java 客户端。
如果需要,请使用 Lettuce
一个更高级的 Java 客户端,还支持异步和反应式连接。
以下部分介绍了如何安装Jedis
并连接您的应用程序
添加到 Redis 数据库。
Jedis
需要正在运行的 Redis 或 Redis Stack 服务器。请参阅 Redis 安装说明入门。
安装
要包括Jedis
作为应用程序中的依赖项,编辑依赖项文件,如下所示。
-
如果您使用 Maven:
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>5.2.0</version> </dependency>
-
If you use Gradle:
repositories { mavenCentral() } //... dependencies { implementation 'redis.clients:jedis:5.2.0' //... }
-
If you use the JAR files, download the latest Jedis and Apache Commons Pool2 JAR files from Maven Central or any other Maven repository.
-
Build from source
Connect and test
The following code opens a basic connection to a local Redis server:
package org.example;
import redis.clients.jedis.UnifiedJedis;
public class Main {
public static void main(String[] args) {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
// Code that interacts with Redis...
jedis.close();
}
}
After you have connected, you can check the connection by storing and
retrieving a simple string value:
...
String res1 = jedis.set("bike:1", "Deimos");
System.out.println(res1); // OK
String res2 = jedis.get("bike:1");
System.out.println(res2); // Deimos
...
More information
Jedis
has a complete API reference available on javadoc.io/.
The Jedis
GitHub repository also has useful docs
and examples including a page about handling
failover with Jedis
See also the other pages in this section for more information and examples:
On this page