jedispool連redis高并發(fā)卡死的問題
java端在使用jedispool 連接redis的時候,在高并發(fā)的時候經(jīng)常死鎖,或報(bào)連接異常,JedisConnectionException,或者getResource 異常等各種問題
在使用jedispool 的時候一定要注意兩點(diǎn)
1。 在獲取 jedisPool和jedis的時候加上線程同步,保證不要創(chuàng)建過多的jedispool 和 jedis
2。 用完Jedis實(shí)例后需要返還給JedisPool
整理了一下redis工具類,通過大量測試和高并發(fā)測試的
package com.caspar.util;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* Redis 工具類
* @author caspar
*
*/
public class RedisUtil {
protected static ReentrantLock lockPool = new ReentrantLock();
protected static ReentrantLock lockJedis = new ReentrantLock();
protected static Logger logger = Logger.getLogger(RedisUtil.class);
//Redis服務(wù)器IP
private static String ADDR_ARRAY = FileUtil.getPropertyValue("/properties/redis.properties", "server");
//Redis的端口號
private static int PORT = FileUtil.getPropertyValueInt("/properties/redis.properties", "port");
//訪問密碼
// private static String AUTH = FileUtil.getPropertyValue("/properties/redis.properties", "auth");
//可用連接實(shí)例的最大數(shù)目,默認(rèn)值為8;
//如果賦值為-1,則表示不限制;如果pool已經(jīng)分配了maxActive個jedis實(shí)例,則此時pool的狀態(tài)為exhausted(耗盡)。
private static int MAX_ACTIVE = FileUtil.getPropertyValueInt("/properties/redis.properties", "max_active");;
//控制一個pool最多有多少個狀態(tài)為idle(空閑的)的jedis實(shí)例,默認(rèn)值也是8。
private static int MAX_IDLE = FileUtil.getPropertyValueInt("/properties/redis.properties", "max_idle");;
//等待可用連接的最大時間,單位毫秒,默認(rèn)值為-1,表示永不超時。如果超過等待時間,則直接拋出JedisConnectionException;
private static int MAX_WAIT = FileUtil.getPropertyValueInt("/properties/redis.properties", "max_wait");;
//超時時間
private static int TIMEOUT = FileUtil.getPropertyValueInt("/properties/redis.properties", "timeout");;
//在borrow一個jedis實(shí)例時,是否提前進(jìn)行validate操作;如果為true,則得到的jedis實(shí)例均是可用的;
private static boolean TEST_ON_BORROW = FileUtil.getPropertyValueBoolean("/properties/redis.properties", "test_on_borrow");;
private static JedisPool jedisPool = null;
/**
* redis過期時間,以秒為單位
*/
public final static int EXRP_HOUR = 60*60; //一小時
public final static int EXRP_DAY = 60*60*24; //一天
public final static int EXRP_MONTH = 60*60*24*30; //一個月
/**
* 初始化Redis連接池
*/
private static void initialPool(){
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[0], PORT, TIMEOUT);
} catch (Exception e) {
logger.error("First create JedisPool error : "+e);
try{
//如果第一個IP異常,則訪問第二個IP
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[1], PORT, TIMEOUT);
}catch(Exception e2){
logger.error("Second create JedisPool error : "+e2);
}
}
}
/**
* 在多線程環(huán)境同步初始化
*/
private static void poolInit() {
//斷言 ,當(dāng)前鎖是否已經(jīng)鎖住,如果鎖住了,就啥也不干,沒鎖的話就執(zhí)行下面步驟
assert ! lockPool.isHeldByCurrentThread();
lockPool.lock();
try {
if (jedisPool == null) {
initialPool();
}
}catch(Exception e){
e.printStackTrace();
} finally {
lockPool.unlock();
}
}
public static Jedis getJedis() {
//斷言 ,當(dāng)前鎖是否已經(jīng)鎖住,如果鎖住了,就啥也不干,沒鎖的話就執(zhí)行下面步驟
assert ! lockJedis.isHeldByCurrentThread();
lockJedis.lock();
if (jedisPool == null) {
poolInit();
}
Jedis jedis = null;
try {
if (jedisPool != null) {
jedis = jedisPool.getResource();
}
} catch (Exception e) {
logger.error("Get jedis error : "+e);
}finally{
returnResource(jedis);
lockJedis.unlock();
}
return jedis;
}
/**
* 釋放jedis資源
* @param jedis
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null && jedisPool !=null) {
jedisPool.returnResource(jedis);
}
}
/**
* 設(shè)置 String
* @param key
* @param value
*/
public synchronized static void setString(String key ,String value){
try {
value = StringUtil.isEmpty(value) ? "" : value;
getJedis().set(key,value);
} catch (Exception e) {
logger.error("Set key error : "+e);
}
}
/**
* 設(shè)置 過期時間
* @param key
* @param seconds 以秒為單位
* @param value
*/
public synchronized static void setString(String key ,int seconds,String value){
try {
value = StringUtil.isEmpty(value) ? "" : value;
getJedis().setex(key, seconds, value);
} catch (Exception e) {
logger.error("Set keyex error : "+e);
}
}
/**
* 獲取String值
* @param key
* @return value
*/
public synchronized static String getString(String key){
if(getJedis() == null || !getJedis().exists(key)){
return null;
}
return getJedis().get(key);
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用@ConfigurationProperties注解獲取為null的解決方法
在SpringBoot中,當(dāng)想需要獲取到配置文件數(shù)據(jù)時,除了可以用 Spring 自帶的@Value注解外,SpringBoot還提供了一種更加方便的方式:@ConfigurationProperties,但我們在通過通過get方法去取值一直為null,本文介紹了使用@ConfigurationProperties注解獲取為null的解決方法2024-09-09
Springboot+Spring Security實(shí)現(xiàn)前后端分離登錄認(rèn)證及權(quán)限控制的示例代碼
本文主要介紹了Springboot+Spring Security實(shí)現(xiàn)前后端分離登錄認(rèn)證及權(quán)限控制的示例代碼,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11
SpringMVC實(shí)現(xiàn)文件上傳和下載功能
這篇文章主要為大家詳細(xì)介紹了SpringMVC實(shí)現(xiàn)文件上傳和下載功能 ,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08
Spring整合TimerTask實(shí)現(xiàn)定時任務(wù)調(diào)度
這篇文章主要介紹了Spring整合TimerTask實(shí)現(xiàn)定時任務(wù)調(diào)度的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12
JVM內(nèi)存模型/內(nèi)存空間:運(yùn)行時數(shù)據(jù)區(qū)
這篇文章主要介紹了JVM內(nèi)存模型/內(nèi)存空間的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)Java虛擬機(jī),感興趣的朋友可以了解詳細(xì),希望能夠給你帶來幫助2021-08-08
Java設(shè)計(jì)模式以虹貓藍(lán)兔的故事講解橋接模式
橋接是用于把抽象化與實(shí)現(xiàn)化解耦,使二者可以獨(dú)立變化。這種類型的設(shè)計(jì)模式屬于結(jié)構(gòu)型模式,它通過提供抽象化和實(shí)現(xiàn)化之間的橋接結(jié)構(gòu),來實(shí)現(xiàn)二者的解耦。這種模式涉及到一個作為橋接的接口,使得實(shí)體類的功能獨(dú)立于接口實(shí)現(xiàn)類。這兩種類型的類可被結(jié)構(gòu)化改變而互不影響2022-04-04
Java編程構(gòu)造方法與對象的創(chuàng)建詳解
這篇文章主要介紹了Java編程構(gòu)造方法與對象的創(chuàng)建詳解,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11
IDEA?Debug過程中使用Drop?Frame或Reset?Frame實(shí)現(xiàn)操作回退的方法
在IDEA中就提供了一個幫助你回退代碼的機(jī)會,但這個方法并不是萬能的,好了,下面就來具體說說IDEA?Debug過程中使用Drop?Frame或Reset?Frame實(shí)現(xiàn)操作回退的方法,感興趣的朋友一起看看吧2022-04-04

