以下是使用Jedis连接池的示例代码:
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisConnectionPool {
private static JedisPool pool;
public static void main(String[] args) {
// 创建连接池配置对象
JedisPoolConfig config = new JedisPoolConfig();
// 设置最大连接数
config.setMaxTotal(20);
// 设置最大空闲连接数
config.setMaxIdle(5);
// 创建连接池对象,指定Redis服务器地址和端口号
pool = new JedisPool(config, "localhost", 6379);
// 获取连接
Jedis jedis = pool.getResource();
try {
// 执行操作
jedis.set("key", "value");
System.out.println(jedis.get("key"));
} finally {
// 释放连接
jedis.close();
}
// 关闭连接池
pool.close();
}
}
在这个例子中,我们首先创建了一个JedisPoolConfig对象,并设置了最大连接数和最大空闲连接数。然后,我们创建了一个JedisPool对象,并传入连接池配置对象、Redis服务器地址和端口号。接着,我们从连接池中获取一个Jedis实例,并执行了一些操作。最后,我们释放了Jedis连接并关闭了连接池。