Redis Pool--Java
配置文件
#redis conf ADDR=127.0.0.1
PORT=
AUTH= #session timeout
TIMEOUT= MAX_ACTIVE=
MAX_IDLE=
MIN_IDLE=
MAX_WAIT=
RedisPool.java
public final class RedisPool { private static JedisPool jedisPool = null; // 最大连接数:可同时建立的最大链接数
private static int max_acti; // 最大空闲数:空闲链接数大于maxIdle时,将进行回收
private static int max_idle; // 最小空闲数:低于minIdle时,将创建新的链接
private static int min_idle; // 最大等待时间:单位ms
private static int max_wait; private static String addr; private static int port; private static String auth; // session timeout by seconds
private static int session_timeout; private RedisPool() {
} /**
* get properties and init RedisPool
*/
static {
Properties pps = new Properties();
InputStream in;
try {
in = new BufferedInputStream(new FileInputStream("src"+File.separator+"conf"+File.separator+"redispool.properties"));
pps.load(in); addr = pps.getProperty("ADDR");
auth = pps.getProperty("AUTH");
port = Integer.parseInt(pps.getProperty("PORT"));
session_timeout = Integer.parseInt(pps.getProperty("TIMEOUT"));
max_acti = Integer.parseInt(pps.getProperty("MAX_ACTIVE"));
max_idle = Integer.parseInt(pps.getProperty("MAX_IDLE"));
min_idle = Integer.parseInt(pps.getProperty("MIN_IDLE"));
max_wait = Integer.parseInt(pps.getProperty("MAX_WAIT")); JedisPoolConfig config = new JedisPoolConfig();
config.setMaxActive(max_acti);
config.setMaxIdle(max_idle);
config.setMaxWait(max_wait);
config.setMinIdle(min_idle);
jedisPool = new JedisPool(config, addr, port, 1000, auth); } catch (Exception e) {
throw new RuntimeException("jedisPool init error" + e.getMessage());
} } /**
* get jedis resource
*/
public synchronized static Jedis getJedis() {
if (jedisPool != null) {
return jedisPool.getResource();
} else {
throw new RuntimeException("jedisPool is null");
}
} /**
* get value map by key
*
* @param key
* @return map
*/
public static Map<String, String> getHashValue(String key) {
Jedis jedis = getJedis();
Map<String, String> map = new HashMap<String, String>();
Iterator<String> iter = jedis.hkeys(key).iterator();
while (iter.hasNext()) {
String mkey = iter.next();
map.put(mkey, jedis.hmget(key, mkey).get(0));
}
jedisPool.returnResource(jedis);
return map;
} /**
* set value by key and map value
*
* @param key
* @param hash
*/
public static void setHashValue(String key, Map<String, String> hash) {
Jedis jedis = getJedis();
jedis.hmset(key, hash);
jedis.expire(key, session_timeout);
jedisPool.returnResource(jedis);
} /**
* remove value by key
*
* @param key
*/
public static void remove(String key) {
Jedis jedis = getJedis();
jedis.del(key);
jedisPool.returnResource(jedis);
} /**
* expire session time to session_timeout
*
* @param key
*/
public static void expire(String key) {
Jedis jedis = getJedis();
jedis.expire(key, session_timeout);
jedisPool.returnResource(jedis);
} /**
* return jedis resource
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
} }