目录
1、JedisPool的应用
1.1 基本应用
1.2 封装应用
1.3 增加超时重试
2、JedisPool配置
2.1 工厂配置
2.2 资源池配置
Jedis提供了连接池JedisPool。由于Jedis对象不是线程安全的,所以一般会从连接池中取出一个Jedis对象独占,使用完毕后再归还给连接池。
maven依赖:
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.1.0</version>
</dependency>
1、JedisPool的应用
1.1 基本应用
资源池简单应用代码示例:
// 获取连接池
JedisPool pool = new JedisPool);
// 从资源池中拿出可以链接对象
// 用try-with-resource自动调用close方法归还资源
tryJedis jedis = pool.getResource);) {
// 应用程序执行操作
}
1.2 封装应用
上述写法,如果使用者没有使用try-with-resource并且忘记了归还资源,可以对JedisPool做一层封装,将归还资源的操作封装起来。
1、资源池:
public class RedisPool {
private JedisPool pool;
public RedisPool) {
this.pool = new JedisPool);
}
/**
* 执行任务
*
* @param callable
*/
public void executeRedisCallable callable) {
tryJedis jedis = pool.getResource)) {
callable.calljedis);
}
}
}
2、回调接口:
public interface RedisCallable {
/**
* 回调方法,执行需要执行的任务
*
* @param jedis jedis
*/
void callJedis jedis);
}
3、使用:
public class RedisMain {
public static void mainString[] args) {
RedisPool pool = new RedisPool);
pool.executejedis) -> {
System.out.printlnjedis.get"key"));
});
}
}
1.3 增加超时重试
网络抖动情况下,需要增加超时重试机制,在捕获到JedisConnectionException时可以进行重试。
可以按如下方式改造资源池:
public class RedisPool {
/**
* 最大重试次数
*/
private static final int MAX_RETRY = 3;
private JedisPool pool;
public RedisPool) {
this.pool = new JedisPool);
}
/**
* 执行任务
*
* @param callable
*/
public void executeRedisCallable callable) {
int count = 0;
try Jedis jedis = pool.getResource)) {
executecallable, jedis, count);
}
}
private void executeRedisCallable callable, Jedis jedis, int count) {
try {
callable.calljedis);
} catch JedisConnectionException e) {
if count < MAX_RETRY) {
executecallable, jedis, ++count);
} else {
throw e;
}
}
}
}
2、JedisPool配置
JedisPool入参最多的构造器:
public JedisPoolfinal GenericObjectPoolConfig poolConfig, final String host, int port,
final int connectionTimeout, final int soTimeout, final String password, final int database,
final String clientName) {
superpoolConfig, new JedisFactoryhost, port, connectionTimeout, soTimeout, password,
database, clientName));
}
上述参数可以分成两部分:资源池配置,以及工厂配置。
2.1 工厂配置
JedisFactory的主要功能为管理(创建,关闭,验证)redis的连接客户端jedis。从连接池获取jedis连接资源,实际上看是从JedisPool的父类pool中获取,而pool又委托给JedisFactory,最后由JedisFactory创建redis连接客户端jedis。
- host:目标服务实例的域名或ip
- port:目标服务器的端口(Redis默认端口号是6379)
- connectionTimeout:连接超时时间
- soTimeout:socket超时时间
- password:密码
- database:数据库
- clientName:生产的客户端实例名称
2.2 资源池配置
资源池JedisPool使用GenericObjectPool的实例来传入配置,而GenericObjectPool是BaseGenericObjectPool的子类。
核心参数:
- maxTotal:最大连接数;
- maxIdle:最大空闲连接数;
- minIdle:最小空闲连接数;
- blockWhenExhausted:表示当pool中的jedis实例都被分配完时,是否要进行阻塞;
- maxWaitMillis:当blockWhenExhausted为true时,最大的阻塞时长。
空闲连接资源检测相关:
- testOnCreate:在创建Jedis实例时,测试连接可用性,默认关闭,如果打开,则保证创建的都是连接可用的Jedis实例;
- testOnBorrow:在资源池借出Jedis实例时,测试连接可用性,默认关闭,如果打开,则保证借出的都是可用的;
- testOnReturn:在Jedis归还Jedis资源池时,测试连接可用性,默认关闭;
- testWhileIdle:表示有一个idle object evitor线程对空闲的Jedis实例进行扫描,如果验证失败,此Jedis实例会被从资源池中删除掉;这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义。
空闲连接资源驱逐相关:
- timeBetweenEvictionRunsMillis:表示idle object evitor两次扫描之间要sleep的毫秒数;
- numTestsPerEvictionRun:表示idle object evitor每次扫描的最多的对象数;
- minEvictableIdleTimeMillis:空闲驱逐时间,表示一个对象至少停留在idle状态的最短时间,然后才能被idle object evitor扫描并驱逐;这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义;
- softMinEvictableIdleTimeMillis:软空闲驱逐时间,在minEvictableIdleTimeMillis基础上,还需要检测至少minIdle个对象已经在资源池里,才会进行驱逐;
- lifo:当借出的资源时,是使用LIFO(last in first out)策略,借出最新使用的资源;还是使用FIFO策略,借出最久没有使用的资源。默认为true,即LIFO;
- evictionPolicy:驱逐策略,接口,默认实现逻辑:资源的空闲毫秒数,如果大于空闲驱逐时间minEvictableIdleTimeMillis,或大于softMinEvictableIdleTimeMillis且当前的空闲资源数量大于配置的最小空闲资源数量,则进行驱逐
BaseGenericObjectPool的配置如下:
private volatile int maxTotal =
GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL;
private volatile boolean blockWhenExhausted =
BaseObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED;
private volatile long maxWaitMillis =
BaseObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS;
private volatile boolean lifo = BaseObjectPoolConfig.DEFAULT_LIFO;
private final boolean fairness;
private volatile boolean testOnCreate =
BaseObjectPoolConfig.DEFAULT_TEST_ON_CREATE;
private volatile boolean testOnBorrow =
BaseObjectPoolConfig.DEFAULT_TEST_ON_BORROW;
private volatile boolean testOnReturn =
BaseObjectPoolConfig.DEFAULT_TEST_ON_RETURN;
private volatile boolean testWhileIdle =
BaseObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE;
private volatile long timeBetweenEvictionRunsMillis =
BaseObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
private volatile int numTestsPerEvictionRun =
BaseObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
private volatile long minEvictableIdleTimeMillis =
BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
private volatile long softMinEvictableIdleTimeMillis =
BaseObjectPoolConfig.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
private volatile EvictionPolicy<T> evictionPolicy;
private volatile long evictorShutdownTimeoutMillis =
BaseObjectPoolConfig.DEFAULT_EVICTOR_SHUTDOWN_TIMEOUT_MILLIS;
GenericObjectPool的配置如下:
/**
* The default value for the {@code maxTotal} configuration attribute.
* @see GenericObjectPool#getMaxTotal)
*/
public static final int DEFAULT_MAX_TOTAL = 8;
/**
* The default value for the {@code maxIdle} configuration attribute.
* @see GenericObjectPool#getMaxIdle)
*/
public static final int DEFAULT_MAX_IDLE = 8;
/**
* The default value for the {@code minIdle} configuration attribute.
* @see GenericObjectPool#getMinIdle)
*/
public static final int DEFAULT_MIN_IDLE = 0;
private int maxTotal = DEFAULT_MAX_TOTAL;
private int maxIdle = DEFAULT_MAX_IDLE;
private int minIdle = DEFAULT_MIN_IDLE;