redis连接池使用及配置解释
2021-07-01 本文已影响0人
小KKKKKKKK
一、redis资源池的使用
以maven工程为例
pom.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>redisDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>16</maven.compiler.source>
<maven.compiler.target>16</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
</project>
代码
package test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* @title: redisDemo
* @Author xiaoK
* @Date: 2021/6/30 16:32
* @Version 1.0
*/
public class redisDemo {
public static void main(String[] args) {
//构建redis资源池配置
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
//配置redis资源池
jedisPoolConfig.setMaxTotal(1000);
//根据jedisPoolConfig构建redis资源池
JedisPool jedisPool = new JedisPool(jedisPoolConfig, "localhost", 6379);
//在redis资源池里构建redis连接
Jedis jedis = jedisPool.getResource();
//对redis操作
String result = jedis.get("abc");
//将redis连接归还给redis资源池
jedis.close();
}
}
二、配置
redis资源池中的配置有很多,如下:
配置 | 解释 | 默认值 | 备注 |
---|---|---|---|
MaxTota | 最大连接数 | 8 | |
MaxIdle | 允许最大空闲的连接数 | 8 | |
MinIdle | 允许最少空闲的连接数 | 0 | |
BlockWhenExhausted | 当资源池用尽后,调用是否要等待 | true | 只有为true时,与MaxWaitMillis 参数一起使用 |
MaxWaitMillis | 当资源池连接用尽后,调用等待最长时间 | -1 | 单位为毫秒,-1为永不超时 |
TestOnBorrow | 向资源池申请连接时,判断连接是否有效,无效连接会被移除 | false | |
TestOnReturn | 向资源池归还连接时,判断连接是否有效 | false | |
JmxEnabled | 是否开启jmx监控 | true | |
TestWhileIdle | 是否开启空闲资源监测 | false | 当为true时,与TimeBetweenEvictionRunsMillis 配合使用 |
TimeBetweenEvictionRunsMillis | 空闲资源监测周期 | -1 | 单位为毫秒,-1为不检测 |
MinEvictableIdleTimeMillis | 达到资源池中空闲时间最小时间后空闲资源将被移除 | 18000 | 单位为毫秒 |
NumTestsPerEvictionRun | 做空闲资源检测时,每次的采样数 | 3 | -1为对所有连接做空闲检测 |