1. 程式人生 > 其它 >使用Jedis在高併發報錯 (java.net.SocketException: Connection reset by peer: socket write error)

使用Jedis在高併發報錯 (java.net.SocketException: Connection reset by peer: socket write error)

onnection reset by peer: socket write error錯誤分析: 常出現的Connection reset by peer: 原因可能是多方面的,不過更常見的原因是: ①:伺服器的併發連線數超過了其承載量,伺服器會將其中一些連線Down掉; ②:客戶關掉了瀏覽器,而伺服器還在給客戶端傳送資料; ③:瀏覽器端按了Stop

1.報錯資訊

java.lang.reflect.InvocationTargetException: null
	at sun.reflect.GeneratedMethodAccessor15.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	....
	at java.lang.Thread.run(Unknown Source)
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Connection reset by peer: socket write error
	at redis.clients.jedis.Connection.flush(Connection.java:334)
	at redis.clients.jedis.Connection.getBinaryBulkReply(Connection.java:257)
	at redis.clients.jedis.BinaryJedis.get(BinaryJedis.java:244)
	......
	... 15 common frames omitted
Caused by: java.net.SocketException: Connection reset by peer: socket write error
	at java.net.SocketOutputStream.socketWrite0(Native Method)
	at java.net.SocketOutputStream.socketWrite(Unknown Source)
	at java.net.SocketOutputStream.write(Unknown Source)
	at redis.clients.util.RedisOutputStream.flushBuffer(RedisOutputStream.java:52)
	at redis.clients.util.RedisOutputStream.flush(RedisOutputStream.java:216)
	at redis.clients.jedis.Connection.flush(Connection.java:331)
	... 22 common frames omitted

所以本問題是由 ①造成的

2.修改之前的程式碼

初始化jedis的程式碼

/**
  * 在多執行緒環境同步初始化
  */
 private static synchronized void poolInit() {
     if (pool == null) {
         createJedisPool();
     }

 }

* 獲取一個jedis 物件
  *
  * @return
  */
 public static Jedis getJedis() {

     if (pool == null) {
         poolInit();
     }
 
     return pool.getResource();
    
      
 }

使用jedis的程式碼

private static Jedis jedis = JedisPoolUtil.getJedis();

public static Object getObject(String key) {
      if(exists(key)){
          return deserialize(jedis.get(key.getBytes()));
      }
      return null;
  }

3.修改之後的程式碼

初始化jedis的程式碼

/**
 * 獲取一個jedis 物件
 *
 * @return
 */
public static Jedis getJedis() {

    if (pool == null) {
        poolInit();
    }
    //如果沒有以下程式碼會造成初始化的jedis拿不到 jedis物件
    Jedis jedis = null;
    try {
        if (pool != null) {
            jedis = pool.getResource();
        }
    }
    catch (Exception e) {
        logger.error("獲取redis失敗 : {}" + ExceptionUtils.getStackTrace(e));
    }
    return jedis;
}

使用jedis的程式碼

/**
    * 讀取物件
    *
    * @param key
    * @return
    */
   public static Object getObject(String key) {
       if (exists(key)) {
           //初始化jedis用完之後關閉連線
           Jedis jedis = JedisPoolUtil.getJedis();
           Object object = deserialize(jedis.get(key.getBytes()));
           jedis.close();
           return object;
       }
       return null;
   }

本文參與騰訊雲自媒體分享計劃,歡迎正在閱讀的你也加入,一起分