1. 程式人生 > >Java工具類之——RedisUtils類

Java工具類之——RedisUtils類

同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();
	}
}