1、如何使用
| <dependency> |
| <groupId>redis.clients</groupId> |
| <artifactId>jedis</artifactId> |
| <version>2.9.0</version> |
| </dependency> |
| @Test |
| public void testJedis() { |
| |
| Jedis jedis = new Jedis("127.0.0.1", 6379); |
| |
| jedis.set("name", "zzw"); |
| String name = jedis.get("name"); |
| System.out.println(name); |
| |
| jedis.close(); |
| } |
2、读写 Redis 数据
| @Test |
| public void testList() { |
| |
| Jedis jedis = new Jedis("127.0.0.1", 6379); |
| |
| jedis.lpush("list1", "a", "b", "c"); |
| jedis.rpush("list1", "x", "y", "z"); |
| List<String> list1 = jedis.lrange("list1", 0, -1); |
| list1.forEach(System.out::println); |
| |
| jedis.close(); |
| } |
| @Test |
| public void testHash() { |
| |
| Jedis jedis = new Jedis("127.0.0.1", 6379); |
| |
| jedis.hset("hash1", "name", "zhangsan"); |
| jedis.hset("hash1", "age", "18"); |
| Map<String, String> map = jedis.hgetAll("hash1"); |
| map.forEach((key, value) -> System.out.println(key + ": " + value)); |
| |
| jedis.close(); |
| } |
3、Jedis 简易工具类开发
| |
| redis.host=127.0.0.1 |
| redis.port=6379 |
| redis.maxTotal=30 |
| redis.maxIdle=10 |
| import java.util.ResourceBundle; |
| |
| public class JedisUtil { |
| |
| private static final JedisPool jp; |
| private static final String host; |
| private static final int port; |
| private static final int maxTotal; |
| private static final int maxIdle; |
| |
| static { |
| ResourceBundle rb = ResourceBundle.getBundle("redis"); |
| host = rb.getString("redis.host"); |
| port = Integer.parseInt(rb.getString("redis.port")); |
| maxTotal = Integer.parseInt(rb.getString("redis.maxTotal")); |
| maxIdle = Integer.parseInt(rb.getString("redis.maxIdle")); |
| |
| JedisPoolConfig config = new JedisPoolConfig(); |
| config.setMaxTotal(maxTotal); |
| config.setMaxIdle(maxIdle); |
| |
| jp = new JedisPool(config, host, port); |
| } |
| |
| public static Jedis getJedis() { |
| return jp.getResource(); |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步