为什么要使用配置文件
之所以要使用配置文件,目的在于降低代码的耦合性,提高代码的复用性,即争取做到代码敲好之后不再需要进行更改,只对配置文件修改就可以达成修改代码功能的目的。下面就细说一下Jedis线程池工具类的开发,来说一下Properties配置文件的使用
配置文件如下:
host=localhost
port=6379
maxTotal=50
maxIdle=10
如下是一个线程池工具类的开发过程,首先以一个static代码块进行了必要的配置。因为static代码块中的语句会随着类的加载一起加载,因此通过静态代码块进行配置代码的运行。
第一步通过类加载器获得输入流,而后新建Properties对象,用Properties对象的load方法加载文件,就可以获得文件当中的键值对,利用getProperty方法就可以获得键值对的值。
public class JedisPoolUtils {
private static JedisPool jedisPool;
static{
//读取配置文件
InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
//创建 properties对象
Properties prop = new Properties();
//读取properties文件当中的数据
try {
prop.load(is);
} catch (IOException e) {
e.printStackTrace();
}
//建立连接池进行参数的配置
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(Integer.parseInt(prop.getProperty("maxTotal")));
jedisPoolConfig.setMaxIdle(Integer.parseInt(prop.getProperty("maxIdle")));
jedisPool = new JedisPool(jedisPoolConfig,prop.getProperty("host"),Integer.parseInt(prop.getProperty("port")));
}
public static Jedis getRedis(){
return jedisPool.getResource();
}
}
下面是该工具类的调用实例
@Test
public void test(){
Jedis jedis = JedisPoolUtils.getRedis();
jedis.set("username","mactavish");
System.out.println(jedis.get("username"));
jedis.close();
}