同C3P0一样,这个是需要配置文件的类,配置文件的格式为properties格式,放在src目录之下,需要用到的工具包为两个,分别是:commons-pool2-2.3.jar和jedis-2.7.0.jar
maxIdle=20
maxTotal=100
minIdle=10
host=192.168.75.140
port=6379
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtil {
private static JedisPoolConfig poolConfig = new JedisPoolConfig();
private static JedisPool pool ;
static{
//解析配置文件
try {
Properties properties = new Properties();
//使用类加载器 加载配置文件
properties.load(RedisUtil.class.getClassLoader().getResourceAsStream("redis.properties"));
int maxIdle =Integer.parseInt( properties.getProperty("maxIdle"));
int maxTotal =Integer.parseInt( properties.getProperty("maxTotal"));
int minIdle =Integer.parseInt( properties.getProperty("minIdle"));
String host =properties.getProperty("host");
int port =Integer.parseInt( properties.getProperty("port"));
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMaxTotal(maxTotal);
poolConfig.setMinIdle(minIdle);
pool= new JedisPool(poolConfig,host, port);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static Jedis getConnection(){
return pool.getResource();
}
public static void close(){
pool.close();
}
}