jedis

本文最后更新于 2024年4月26日 凌晨

redis/jedis: Redis Java client designed for performance and ease of use. https://github.com/redis/jedis

文件树

1
2
3
4
5
6
7
8
9
10
src/
├───main/java/com/cc01cc/jedis/util/
│ │
│ └───JedisConnectionFactory.java

└───test/java/com/cc01cc/test/

├───TestJedis.java

└───TestJedisPool.java

引入依赖

1
2
3
4
5
6
<!-- pom.xml -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.3.0</version>
</dependency>

建立连接

1
2
3
4
5
6
7
8
9
10
// TestJedis.java
@BeforeEach
void setUp() {
// 1. 建立连接
jedis = new Jedis("192.168.0.104", 6379);
// 2. 设置密码
jedis.auth("abc123");
// 3. 选择库
jedis.select(0);
}

操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// TestJedis.java
@Test
void testString() {
// 存入数据
String result = jedis.set("name", "testName");
System.out.println("result = " + result);

// 获取数据
String name = jedis.get("name");
System.out.println("name = " + name);
}
@Test
void testHash() {
// 插入 hash 数据
jedis.hset("user:1", "name", "Jack");
jedis.hset("user:1", "age", "21");

// 获取
Map<String, String> map = jedis.hgetAll("user:1");
System.out.println(map);
}

释放资源

1
2
3
4
5
6
7
// TestJedis.java
@AfterEach
void tearDown() {
if (jedis != null) {
jedis.close();
}
}

Jedis 连接池

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// JedisConnectionFactory.java
public class JedisConnectionFactory {
private static final JedisPool jedisPool;

static {
// 配置连接池
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(8);
poolConfig.setMaxIdle(8);
poolConfig.setMinIdle(0);
poolConfig.setMaxWait(Duration.ofMillis(1000));

// 创建连接池对象
jedisPool = new JedisPool(poolConfig,
"192.168.0.104", 6379, 1000, "abc123");
}

public static Jedis getJedis() {
return jedisPool.getResource();
}
}

// TestJedisPool.java
@BeforeEach
void setUp() {
// 建立连接
jedis = JedisConnectionFactory.getJedis();
}


jedis
https://blog.cc01cc.cn/2022/11/19/java-redis-jedis/
作者
零一/cc01cc(zeo)
发布于
2022年11月19日
更新于
2024年4月26日
许可协议