標籤:
package com.wanhua.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import play.Play;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* Redis工具類,用於擷取RedisPool. 參考官網說明如下: You shouldn‘t use the same instance from different threads because you‘ll have strange errors. And sometimes creating lots of Jedis instances is not good enough because it means lots of sockets and connections, which leads to strange errors as well. A single Jedis instance is not threadsafe! To avoid these problems, you should use JedisPool, which is a threadsafe pool of network connections. This way you can overcome those strange errors and achieve great performance. To use it, init a pool: JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost"); You can store the pool somewhere statically, it is thread-safe. JedisPoolConfig includes a number of helpful Redis-specific connection pooling defaults. For example, Jedis with JedisPoolConfig will close a connection after 300 seconds if it has not been returned.
*
* @author bqwang
*/
public class JedisUtil {
private static Logger logger = Logger.getLogger(JedisUtil.class.getName()); // logger
/**
* 私人構造器.
*/
private JedisUtil() {
}
private static Map<String, JedisPool> maps = new HashMap<String, JedisPool>();
/**
* 擷取串連池.
*
* @return 串連池執行個體
*/
private static JedisPool getPool(String ip, int port) {
String key = ip + ":" + port;
JedisPool pool = null;
if (!maps.containsKey(key)) {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(Integer.parseInt(Play.configuration.getProperty("redis.pool.maxIdle")));
config.setMaxTotal(Integer.parseInt(Play.configuration.getProperty("redis.pool.maxTotal")));
config.setTestOnBorrow(Play.configuration.getProperty("redis.pool.testOnBorrow") == "true" ? true : false);
config.setTestOnReturn(Play.configuration.getProperty("redis.pool.testOnReturn") == "true" ? true : false);
try {
/**
* 如果你遇到 java.net.SocketTimeoutException: Read timed out exception的異常資訊 請嘗試在構造JedisPool的時候設定自己的逾時值. JedisPool預設的逾時時間是2秒(單位毫秒)
*/
pool = new JedisPool(config, ip, port, Integer.parseInt(Play.configuration.getProperty("redis.pool.timeout")));
maps.put(key, pool);
} catch (Exception e) {
e.printStackTrace();
}
} else {
pool = maps.get(key);
}
return pool;
}
/**
* 類級的內部類,也就是靜態成員式內部類,該內部類的執行個體與外部類的執行個體 沒有綁定關係,而且只有被調用到時才會裝載,從而實現了消極式載入。
*/
private static class RedisUtilHolder {
/**
* 靜態初始化器,由JVM來保證安全執行緒
*/
private static JedisUtil instance = new JedisUtil();
}
/**
* 當getInstance方法第一次被調用的時候,它第一次讀取 RedisUtilHolder.instance,導致RedisUtilHolder類得到初始化;而這個類在裝載並被初始化的時候,會初始化它的靜 態域,從而建立RedisUtil的執行個體,由於是靜態域,因此只會在虛擬機器裝載類的時候初始化一次,並由虛擬機器來保證它的執行緒安全性。 這個模式的優勢在於,getInstance方法並沒有被同步,並且只是執行一個域的訪問,因此延遲初始化並沒有增加任何訪問成本。
*/
public static JedisUtil getInstance() {
return RedisUtilHolder.instance;
}
/**
* 擷取Redis執行個體.
*
* @return Redis工具類執行個體
*/
public Jedis getJedis() {
// logger.info("get getJedis------");
Jedis jedis = null;
int count = 0;
do {
String ip = Play.configuration.getProperty("redis.server.ip");
// logger.info("get ip------"+ip);
int port = Integer.parseInt(Play.configuration.getProperty("redis.server.port"));
// logger.info("get port------"+port);
try {
jedis = getPool(ip, port).getResource();
} catch (Exception e) {
logger.info("get redis master1 failed!" + e);
// 銷毀對象
getPool(ip, port).returnBrokenResource(jedis);
}
count++;
} while (jedis == null && count < Integer.parseInt(Play.configuration.getProperty("redis.pool.retryTimes")));
// logger.info("get jedis success------");
return jedis;
}
/**
* 釋放redis執行個體到串連池.
*
* @param jedis
* redis執行個體
*/
public static void closeJedis(Jedis jedis) {
String ip = Play.configuration.getProperty("redis.server.ip");
int port = Integer.parseInt(Play.configuration.getProperty("redis.server.port"));
if (jedis != null) {
getPool(ip, port).returnResource(jedis);
}
}
public static void main(String args[]) {
Jedis jds = JedisUtil.getInstance().getJedis();
// 向redis中添加資料
jds.sadd("mb", "test");
// 從redis中取資料
Set<String> resultSet = jds.smembers("mb");
System.out.println("--get--result--from--redis---" + resultSet.toString());
// 清空redis中指定key的訊息
jds.del("mb");
// 清空所有redis中訊息
jds.flushDB();
}
}
redis的使用:擷取redis執行個體的工具類