jedis 连接池对象是 JedisPool
1.下载并导入jar 包到项目中,点击这里下载(commons-pool2-2.3.jar)
2.简单使用
1.创建JedisPool对象
JedisPool jedisPool = new JedisPool();
2.获取连接对象
Jedis jedis = jedisPool.getResource();
3.操作数据
jedis.set("hehe","haha");
String hehe = jedis.get("hehe");
4.归还连接对象到连接池中
jedis.close();
配置jedis连接池
创建连接对象
JedisPoolConfig config = new JedisPoolConfig();
设置最大连接数
config.setMaxTotal(50);
设置最大能够保持idel状态的对象数
config.setMaxIdle(10);
使用此配置对象创建连接池对象
JedisPool jedisPool = new JedisPool(config,"localhost",6379);
使用jedis连接池工具类
在 src 根目录下创建一个名称为 jedis.properties 的配置文件,内容如下
host=127.0.0.1
port=6379
maxTotal=50
maxIdle=10
创建一个类,取名为 JedisPoolUtils.java ,写入如下代码
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;
/**
JedisPool工具类
加载配置文件,配置连接池的参数
提供获取连接的方法
*/
public class JedisPoolUtils {
private static JedisPool jedisPool;
static{
//读取配置文件
InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
//创建Properties对象
Properties pro = new Properties();
//关联文件
try {
pro.load(is);
} catch (IOException e) {
e.printStackTrace();
}
//获取数据,设置到JedisPoolConfig中
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
//初始化JedisPool
jedisPool = new JedisPool(config,pro.getProperty("host"),Integer.parseInt(pro.getProperty("port")));
}
/**
* 获取连接方法
*/
public static Jedis getJedis(){
return jedisPool.getResource();
}
}
这时,就可以通过如下代码获取连接对象了
Jedis jedis = JedisPoolUtils.getJedis();