對於redis沒有設置密碼情況,直接去掉類中的密碼即可
package com.practice.utils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.ResourceBundle;
/**
-
〈說明〉
-
〈〉
-
@author lenovo
-
@since 1.0.0
/
public class JedisPoolUtils {
/* 定義最大空閑數 */
private static int MAX_IDLE;/** 定義最小空閑數 */
private static int MIN_IDLE;/** 定義最大連接數 */
private static int MAX_TOTAL;/** 定義遠程IP地址 */
private static String URL;/** 定義連接端口號 */
private static int PORT;/** 定義redis客戶端登錄密碼 */
private static String PASSWORD;/** 定義連接超時時間 */
private static int TIME_OUT;/** 創建JedisPool對象,定義為空,等待初始化 */
private static JedisPool pool = null;/**
- 靜態代碼塊
- 初始化連接池
*/
static {
JedisPoolConfig poolConfig = init();
//初始化連接池對象
pool = new JedisPool(poolConfig, URL, PORT, TIME_OUT, PASSWORD);
}
/**
- 靜態方法獲取Jedis對象
- 獲取前進行非空判斷
- pool如果為空,則返回null
- @return
*/
public synchronized static Jedis getJedis() {
if (pool != null) {
return pool.getResource();
}
return null;
}
/**
- 回收Jedis
- 回收前進行非空判斷
- final Jedis jedis確保傳進來的Jedis對象與returnJedis(Jedis jedis)方法內Jedis對象一致
- @param jedis
- @throws Exception
*/
public static void returnJedis(final Jedis jedis) {
if (jedis != null) {
pool.returnResourceObject(jedis);
}
}
/**
-
靜態方法init()用於初始化配置參數
-
私有方法置於最后
-
@return
*/
private static JedisPoolConfig init() {
//讀取並加載初始化參數
ResourceBundle bundle = ResourceBundle.getBundle("redis");
MAX_IDLE = Integer.valueOf(bundle.getObject("redis.maxIdle").toString());
MIN_IDLE = Integer.valueOf(bundle.getObject("redis.minIdle").toString());
MAX_TOTAL = Integer.valueOf(bundle.getObject("redis.maxTotal").toString());
URL = bundle.getString("redis.url");
PORT = Integer.valueOf(bundle.getObject("redis.port").toString());
PASSWORD = bundle.getString("redis.password");
TIME_OUT = Integer.valueOf(bundle.getObject("redis.timeOut").toString());//創建連接池配置對象
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(MAX_IDLE);
poolConfig.setMinIdle(MIN_IDLE);
poolConfig.setMaxTotal(MAX_TOTAL);
return poolConfig;
}
}
