提供一个使用redis连接池的JedisHelper工具类
public class JedisHelper {
private static JedisPool jedisPool = null;
private static String ADDR = MDMProperies.ADDR;
private static int PORT = MDMProperies.PORT;
private static String AUTH = MDMProperies.AUTH;
private static Integer database = MDMProperies.database;
static {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setBlockWhenExhausted(true);
config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
config.setJmxEnabled(true);
config.setMaxIdle(8);
config.setMaxTotal(200);
config.setMaxWaitMillis(1000 * 100);
config.setTestOnBorrow(true);
if(StringUtils.isNotBlank(AUTH)){
jedisPool = new JedisPool(config, ADDR, PORT, 3000,AUTH);
}else{
jedisPool = new JedisPool(config, ADDR, PORT, 3000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
resource.select(database);
return resource;
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
public static void close(final Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
}
- MDMProperies是我的配置类用来读取配置文件的,略。
- 依赖:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>