环境:
- 操作系统: Ubuntu 20.04
- Redis:6.2.6
- 开发工具:IntelliJ IDEA 2022.1 (Community Edition)
Redis官网( https://redis.io/docs/clients/#java )所推荐的Java客户端有:
- Redisson
- Jedis
- lettuce
等等。本文将介绍 Jedis 和 lettuce 。
Jedis 方法1:手工配置即手工搜索并下载所需的jar包,可以到以下网站搜索:
- https://mvnrepository.com/
- https://search.maven.org/
搜索 jedis ,下载 jedis-4.2.2.jar 文件。
新建项目 test0427_1 :
在项目下创建 lib 目录,把 jedis-4.2.2.jar 复制到这里。
➜ test0427_1 mkdir lib ➜ test0427_1 cp ~/Downloads/jedis-4.2.2.jar lib/ ➜ test0427_1
File -> Project Structure... -> Modules -> Dependencies ,点击 + 图标,选择 JARs or Directories... ,然后选择 jedis-4.2.2.jar 文件:
创建 Test0427.java 文件如下:
package pkg1;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class Test0427 {
public static void main(String[] args) {
JedisPool pool = new JedisPool("localhost", 6379);
try (Jedis jedis = pool.getResource()) {
jedis.set("mykey1", "500");
}
}
}
运行程序,报错如下:
/home/ding/IdeaProjects/test0427_1/src/pkg1/Test0427.java:8:26 java: cannot access org.apache.commons.pool2.impl.GenericObjectPoolConfig class file for org.apache.commons.pool2.impl.GenericObjectPoolConfig not found
从 http://www.bjpowernode.com/tutorial_redis/342.html 可知,还需要下载 commons-pool2 。
搜索 commons-pool2 ,并下载 commons-pool2-2.11.1.jar 文件,按前面的方法将其添加到项目里。
运行程序,报错如下:
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory at redis.clients.jedis.JedisPool.(JedisPool.java:19) at pkg1.Test0427.main(Test0427.java:8) Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520) ... 2 more
继续搜索 slf4j.api ,下载 slf4j-api-2.0.0-alpha7.jar 文件,按前面的方法将其添加到项目里。
运行程序,报错如下:
SLF4J: No SLF4J providers were found. SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details. Exception in thread "main" java.lang.NoClassDefFoundError: com/google/gson/Gson at redis.clients.jedis.CommandObjects.(CommandObjects.java:3655) at redis.clients.jedis.Jedis. (Jedis.java:39) at redis.clients.jedis.JedisFactory.makeObject(JedisFactory.java:181) at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:571) at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:298) at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:223) at redis.clients.jedis.util.Pool.getResource(Pool.java:34) at redis.clients.jedis.JedisPool.getResource(JedisPool.java:364) at pkg1.Test0427.main(Test0427.java:10) Caused by: java.lang.ClassNotFoundException: com.google.gson.Gson at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520) ... 9 more
SLF4J 的错误其实并不影响运行,真正影响运行的是 gson 的错误。继续搜索gson ,下载 gson-2.9.0.jar 文件,按前面的方法将其添加到项目里。
运行程序,报错如下:
SLF4J: No SLF4J providers were found. SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details.
不过也成功了。
如果想移除错误,继续搜索slf4j.simpl ,下载 slf4j-simple-2.0.0-alpha7.jar 文件,按前面的方法将其添加到项目里。
运行程序,这回终于没有任何错误了。
最终所使用的的jar包如下:
方法2:Maven配置手工配置Jedis实在太麻烦,所以显而易见的解决方案是使用Maven来管理依赖。
新建Maven项目test0427_2 :
打开 pom.xml 文件,添加如下内容:
redis.clients jedis 4.2.2
注:需要加到
同样,创建 Test0427.java 文件如下:
package pkg1;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class Test0427 {
public static void main(String[] args) {
JedisPool pool = new JedisPool("localhost", 6379);
try (Jedis jedis = pool.getResource()) {
jedis.set("mykey1", "500");
}
}
}
运行程序,报错如下:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
不过也成功了。
这个错误跟方法1缺少 slf4j-simple-2.0.0-alpha7.jar 文件的错误完全一样。
查看 External Libraries ,可见除了 slf4j-simple-2.0.0-alpha7.jar 以外,已经包含了方法1所添加的那些jar包。
如果想移除错误,在 pom.xml 中添加以下依赖:
org.slf4j slf4j-simple 1.7.32
注:版本是 1.7.32 ,因为 slf4j-api 的版本是 1.7.32 。如果换成别的版本(比如 2.0.0-alpha7 ),貌似不行,仍然报错。
查看 External Libraries ,如下:
方法3:SpringBoot参见下面Lettuce部分的SpringBoot配置。因为Spring Data Redis默认使用的是Lettuce。
Lettuce 方法1:手工配置即手工搜索并下载所需的jar包。可从(https://github.com/lettuce-io/lettuce-core/releases)下载。我看到的最新版本是6.1.8,但是该版本只提供源码下载,需要自己做build,于是我下载了6.1.7的包 lettuce-core-6.1.7.RELEASE-bin.tar.gz 。
解压后得到 lettuce-core-6.1.7.RELEASE.jar 以及其它一些jar包。
新建项目 test0429_1 :
在项目下创建 lib 目录,把 lettuce-core-6.1.7.RELEASE.jar 以及其它所有的jar包都复制到这里。
File -> Project Structure... -> Modules -> Dependencies ,点击 + 图标,选择 JARs or Directories... ,然后选择 lib 目录下所有的文件:
最终所使用的jar包如下:
创建 Test0429.java 文件如下:
package pkg1;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
public class Test0429 {
public static void main(String[] args) {
RedisURI redisUri = RedisURI.builder()
.withHost("localhost")
.withDatabase(0)
.withPort(6379)
.withTimeout(Duration.of(10, ChronoUnit.SECONDS))
.build();
RedisClient redisClient = RedisClient.create(redisUri);
StatefulRedisConnection conn = redisClient.connect();
RedisCommands command = conn.sync();
command.set("mykey1", "500");
conn.close();
redisClient.shutdown();
}
}
运行程序,OK,测试成功!
方法2:Maven配置新建Maven项目test0429_2 :
打开 pom.xml 文件,添加如下内容:
io.lettuce lettuce-core 6.1.8.RELEASE
注:需要加到
同样,创建 Test0429.java 文件如下:
package pkg1;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
public class Test0429 {
public static void main(String[] args) {
RedisURI redisUri = RedisURI.builder()
.withHost("localhost")
.withDatabase(0)
.withPort(6379)
.withTimeout(Duration.of(10, ChronoUnit.SECONDS))
.build();
RedisClient redisClient = RedisClient.create(redisUri);
StatefulRedisConnection conn = redisClient.connect();
RedisCommands command = conn.sync();
command.set("mykey1", "500");
conn.close();
redisClient.shutdown();
}
}
运行程序,OK,测试成功!
查看 External Libraries ,如下:
注:如果要使用连接池,则需要 commons-pool2 。在 pom.xml 文件中添加如下依赖:
方法3:SpringBootorg.apache.commons commons-pool2 2.11.1
打开 https://start.spring.io/ ,搜索 redis ,添加依赖 Spring Data Redis (Access+Driver) ,如下图所示:
创建项目 test0429_3 ,下载 test0429_3.zip 文件,解压生成项目,并打开。
打开 pom.xml 文件,可见相关的依赖为:
org.springframework.boot spring-boot-starter-data-redis
打开 application.properties 文件,添加Redis的配置信息:
spring.redis.host=localhost spring.redis.port=6379
本例只配置了 host 和 port ,若有其它信息,也可在此配置。
打开 Test04293ApplicationTests.java 文件,添加依赖注入的 StringRedisTemplate ,然后添加一个自定义Test,最终代码如下:
package com.example.test0429_3;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
@SpringBootTest
class Test04293ApplicationTests {
@Autowired
StringRedisTemplate redisTemplate;
@Test
void contextLoads() {
}
@Test
void myTest() {
redisTemplate.opsForValue().set("mykey1", "500");
}
}
运行 myTest ,OK,测试成功!
注:这里使用的是 StringRedisTemplate 而不是 RedisTemplate 。如果是后者,运行也OK,但是不知道set到哪里去了,从Redis的命令行检查, mykey1 的值并没有变化。具体原因待查。
最终项目结构如下:
参考- https://redis.io/
- https://github.com/redis/jedis
- https://mvnrepository.com/
- https://search.maven.org/
- https://lettuce.io/
- https://github.com/lettuce-io/
- http://www.bjpowernode.com/tutorial_redis/342.html



