ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
连接池使用步骤如下: 1. 导入依赖包 大多数的JAR包你可以到[Maven仓库](https://mvnrepository.com/)中找到 | JAR包 | | --- | | commons-pool2-2.8.1.jar<br/>slf4j-api-1.7.30.jar | 2. 将`jedis.properties`配置放在src目录下 ```xml host=localhost port=6379 maxTotal=50 maxIdle=10 #...当然还有很多的配置,这里就不配置了 ``` 3. 封装`JedisPoolUtils.java`用于建立连接和关闭连接 ```java package common; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class JedisPoolUtils { private static JedisPool jedisPool; static { InputStream inputStream = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties"); Properties properties = new Properties(); try { properties.load(inputStream); } catch (IOException e) { e.printStackTrace(); } JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(Integer.parseInt(properties.getProperty("maxTotal"))); config.setMaxIdle(Integer.parseInt(properties.getProperty("maxIdle"))); jedisPool = new JedisPool(config, properties.getProperty("host"), Integer.parseInt(properties.getProperty("port"))); } /** * 连接Redis数据库 * @return Jedis */ public static Jedis getJedis() { return jedisPool.getResource(); } /** * 关闭与Redis数据的连接 * @param jedis */ public static void close(Jedis jedis) { jedis.close(); } } ``` 4. 进行测试 ```java @org.junit.Test public void test() throws InterruptedException { Jedis jedis = JedisPoolUtils.getJedis(); jedis.zadd("sorted", 1.0, "张三"); jedis.zadd("sorted", 3.0, "李四"); jedis.zadd("sorted", 2.0, "王五"); // 根据范围获取 Set<String> sorted = jedis.zrange("sorted", 0, -1); System.out.println("--根据范围获取---" + sorted); // 根据分数范围获取 sorted = jedis.zrangeByScore("sorted", 2, 3.0); System.out.println("--根据分数范围获取---" + sorted); JedisPoolUtils.close(jedis); } ``` ![](https://img.kancloud.cn/ff/d0/ffd01f903fccfd0b113d5c8313df99c6_926x222.png)