Jedis的连接池是自带的,不需要三方包
pom.xml下导入maven坐标
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
编写测试代码
// 创建JedisPool配置对象
JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
//设置连接池配置参数
jedisPoolConfig.setMaxTotal(50);
jedisPoolConfig.setMaxIdle(10);
//创建连接池对象
JedisPool jedisPool=new JedisPool(jedisPoolConfig,"192.168.182.129");
//获取jedis对象
Jedis jedis = jedisPool.getResource();
//设置密码
jedis.auth("111111");
String name = jedis.get("name");
System.out.println(name);
jedis.close();
为了方便使用,我们可以编写JedisUtils工具类,将配置从jedis.properties中读取进行配置。
jedis.properties内容,将文件放入maven resources目录下,不是maven项目放入src目录下。
#最大活动对象数
redis.pool.maxTotal=1000
#最大能够保持idle状态的对象数,数据库连接的最大空闲时间。超过空闲时间,数据库连
#接将被标记为不可用,然后被释放。设为0表示无限制。
redis.pool.maxIdle=100
#最小能够保持idel状态的对象数
redis.pool.minIdle=50
#当池内没有返回对象时,最大等待时间
redis.pool.maxWaitMillis=10000
#当调用borrow Object方法时,是否进行有效性检查
redis.pool.testOnBorrow=true
#当调用return Object方法时,是否进行有效性检查
redis.pool.testOnReturn=true
#“空闲链接”检测线程,检测的周期,毫秒数。如果为负值,表示不运行“检测线程”。默认为-1.
redis.pool.timeBetweenEvictionRunsMillis=30000
#向调用者输出“链接”对象时,是否检测它的空闲超时;
redis.pool.testWhileIdle=true
# 对于“空闲链接”检测线程而言,每次检测的链接资源的个数。默认为3.
redis.pool.numTestsPerEvictionRun=50
#redis服务器的IP
redis.ip=192.168.182.129
#redis服务器的Port
redis.port=6379
#redis服务器的密码
redis.auth=111111
JedisUtils的编写
public class JedisUtils {
private static JedisPool jedisPool;
private static String AUTH;
static{
//读取配置文件
InputStream is = null;
is = JedisUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
//创建Properties对象
Properties pro = new Properties();
//关联文件
try {
pro.load(is);
} catch (IOException e) {
e.printStackTrace();
}
// 将AUTH赋值
AUTH=pro.getProperty("redis.auth");
//获取数据,设置到JedisPoolConfig中
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(Integer.parseInt(pro.getProperty("redis.pool.maxTotal")));
config.setMaxIdle(Integer.parseInt(pro.getProperty("redis.pool.maxIdle")));
//初始化JedisPool
jedisPool = new JedisPool(config,pro.getProperty("redis.ip"),Integer.parseInt(pro.getProperty("redis.port")));
}
/**
* 获取连接方法
*/
public static Jedis getJedis(){
Jedis jedis = jedisPool.getResource();
jedis.auth(AUTH);
return jedis;
}
/**
*
* 释放资源
*/
public static void releaseJedis(Jedis jedis){
if(jedis!=null){
jedis.close();
}
}
}
工具类的测试
@Test
public void testJedisUtils(){
Jedis jedis = JedisUtils.getJedis();
System.out.println(jedis.get("name"));
JedisUtils.releaseJedis(jedis);
}
这里使用Junit请导入坐标
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
测试成功,之后使用过程中我们只需要修改jedis.properties配置文件就可以了,而不用在代码中进行修改。
帮助到您请点赞关注收藏谢谢!!