背景
redis 版本:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
spring版本:4.0.6
实现步骤
1.配置.properties文件
2.配置applicationContext.xml文件
3.实现JedisUtil工具类
详细配置
1.配置.properties文件
一般redis相关配置属性都配置在自定义的properties文件中,本文对应的配置文件为config.properties,具体的配置信息如下:
redis.host=192.168.1.1
redis.port=6379
redis.passworkd=pass
redis.pool.maxTotal=8
redis.pool.maxIdle=8
redis.pool.minIdle=0
redis.pool.maxWait=1000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true
redis.pool.timeOut=1000
2.配置applicationContext.xml文件
redis对象池的配置方式有多重,这里选择的是共享方式
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- maxTotal:最大支持数 maxIdle: 最大能够保持idel状态的对象数 minIdle:最小能够保持idel状态的对象数
maxWaitMillis: 最大呢等待时间
testOnBorrow:在borrow一个jedis实例时,是否提前进行alidate操作
testOnReturn:在return给pool时,是否提前进行validate操作-->
<property name="maxTotal" value="${redis.pool.maxTotal}" />
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<property name="minIdle" value="${redis.pool.minIdle}" />
<property name="maxWaitMillis" value="${redis.pool.maxWait}" />
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
<property name="testOnReturn" value="${redis.pool.testOnReturn}" />
</bean>
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="${redis.host}" />
<constructor-arg index="1" value="${redis.port}" type="int" />
<constructor-arg index="2" value="${redis.pool.timeOut}" type="int" />
<property name="password" value="${redis.passworkd}" />
</bean>
</list>
</constructor-arg>
</bean>
3.实现JedisUtil工具类
工具类中,对象池的加载方式是延迟加载,包含的方法有获取jedis对象和关闭jedis对象
package util.Redis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import util.spring.SpringContextUtil;
/**
* Redis工具类,用于管理RedisPool.
*/
public class JedisUtil {
protected Logger log = LoggerFactory.getLogger(getClass());
private static ShardedJedisPool pool;;
/**
* 获取连接池.
* @return 连接池实例
*/
private static ShardedJedisPool getPool() {
if(pool == null){
pool = SpringContextUtil.getBean(ShardedJedisPool.class);
}
return pool;
}
/**
* 获取Redis实例.
* @return Redis工具类实例
*/
public static ShardedJedis getJedis() {
return getPool().getResource();
}
/**
* 释放redis实例到连接池.
* @param jedis redis实例
*/
@SuppressWarnings("deprecation")
public static void closeJedis(ShardedJedis jedis) {
if(jedis != null) {
getPool().returnResource(jedis);
}
}
}