本文最后更新于 2024年11月24日 晚上
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
| <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>4.3.0</version> </dependency>
|
建立连接
1 2 3 4 5 6 7 8 9 10
| @BeforeEach void setUp() { jedis = new Jedis("192.168.0.104", 6379); jedis.auth("abc123"); jedis.select(0); }
|
操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @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() { 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
| @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
| 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(); } }
@BeforeEach void setUp() { jedis = JedisConnectionFactory.getJedis(); }
|