package com.bj58.zpsender.util;
import java.io.FileReader;
import java.io.Reader;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public final class RedisUtil {
private static Logger LOGGER = LoggerFactory.getLogger(RedisUtil.class);
private static JedisPool jedisPool = null;
public static void initRedisClient(String filePath){
if (null == jedisPool) {
synchronized (RedisUtil.class) {
if (null == jedisPool){
initJedisPool(filePath);
}
}
}
}
private static void initJedisPool(String filePath) {
Properties properties = new Properties();
try {
Reader inStream = new FileReader(filePath+ "/config/redis.properties");
properties.load(inStream);
// Redis服务器IP
String addr = properties.getProperty("address");
// Redis的端口号
int port = Integer.parseInt(properties.getProperty("port"));
// 访问密码
String auth = properties.getProperty("auth");
// 可用连接实例的最大数目,默认值为8;
// 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
int maxActive = Integer.parseInt(properties.getProperty("max_active"));
// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
int maxIdle = Integer.parseInt(properties.getProperty("max_idle"));
//初始化连接数
int minIdle = Integer.parseInt(properties.getProperty("min_idle"));
// 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
int maxWait = Integer.parseInt(properties.getProperty("max_wait"));
int timeout = Integer.parseInt(properties.getProperty("timeout"));;
// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
boolean testOnBorrow = Boolean.parseBoolean(properties.getProperty("test_on_borrow"));
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxActive);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
config.setMaxWaitMillis(maxWait);
config.setTestOnBorrow(testOnBorrow);
if(StringUtils.isNotBlank(auth)){
jedisPool = new JedisPool(config, addr, port, timeout,auth);
}else {
jedisPool = new JedisPool(config, addr, port, timeout);
}
}catch (Exception e) {
LOGGER.error("[RedisUtil 初始化异常] redis error ",e);
}
}
/**
* 获取Jedis实例
*
* @return
*/
public static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
return resource;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 释放jedis资源
*
* @param jedis
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
public static <T> T jedis(JedisHandler<T> handiler) {
Jedis jedis = null;
try {
jedis = RedisUtil.getJedis();
return handiler.handle(jedis);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
RedisUtil.returnResource(jedis);
}
}
return null;
}
}