java redis 连接池
当Jedispool资源池连接用尽后,调用者的最大等待时间(单位为毫秒)。默认值为-1,表示永不超时,不建议使用默认值。#如果该属性为true,表示会用一个专门的线程对空闲的连接进行有效性的检测扫描,默认值为true,表示进行空闲连接的检测。#表示一个Jedis连接至少停留在空闲状态的最短时间,然后才能被空闲连接扫描线程进行有效性检测。#如果有效性检测失败,则表示连接无效,会从资源池中移除该连接。
代码
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.time.Duration;
import java.util.Properties;
//redis 连接池
public class JedisPoolUtils {
private static JedisPool jedisPool;
static {
//读取配置文件
InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
Properties pro = new Properties();
try {
pro.load(is);
} catch (IOException e) {
e.printStackTrace();
}
//创建Jedis配置对象
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
config.setBlockWhenExhausted(Boolean.parseBoolean(pro.getProperty("blockWhenExhausted")));
config.setMaxWait(Duration.ofMillis(Long.parseLong(pro.getProperty("maxWaitMillis"))));
config.setTimeBetweenEvictionRuns(Duration.ofMillis(Long.parseLong(pro.getProperty("timeBetweenEvictionRunsMillis"))));
config.setMinEvictableIdleTime(Duration.ofMillis(Long.parseLong(pro.getProperty("minEvictableIdleTimeMillis"))));
config.setTestWhileIdle(Boolean.parseBoolean(pro.getProperty("testWhileIdle")));
// 初始化
jedisPool = new JedisPool(config,pro.getProperty("host"),
Integer.parseInt(pro.getProperty("port")),
Integer.parseInt(pro.getProperty("timeout")),
pro.getProperty("password"));
}
// 获取连接
public static Jedis getJedis()
{
return jedisPool.getResource();
}
public static void close()
{
jedisPool.close();
}
}
使用:
Jedis jedis = JedisPoolUtils.getJedis();
…
//注意这里不是关闭连接,在JedisPool模式下,jedis.close()会被归还给资源池。
jedis.close()
// 销毁连接池
JedisPoolUtils.close()
配置文件:
#最大连接数
maxTotal=8
#最大空闲连接数
maxIdle=5
#连接满了之后是否等待
blockWhenExhausted=true
#当Jedispool资源池连接用尽后,调用者的最大等待时间(单位为毫秒)。默认值为-1,表示永不超时,不建议使用默认值。
maxWaitMillis=20000
#表示两次空闲连接扫描的活动之间,要睡眠的毫秒数,默认30s
timeBetweenEvictionRunsMillis=30000
#表示一个Jedis连接至少停留在空闲状态的最短时间,然后才能被空闲连接扫描线程进行有效性检测
minEvictableIdleTimeMillis=60000
#如果该属性为true,表示会用一个专门的线程对空闲的连接进行有效性的检测扫描,默认值为true,表示进行空闲连接的检测。
#如果有效性检测失败,则表示连接无效,会从资源池中移除该连接。
testWhileIdle=true
#客户端密码,ip,端口以及超时设置
host=xx
port=6379
password=123456
timeout=10000
更多推荐
所有评论(0)