注意!! Redis使用不當真的可能會導致應用卡死

首先說下問題現象:內網沙盒環境API持續1周出現應用卡死,所有api無響應現象

剛開始當測試拒絕環境響應慢的時候,我們重新一下應用,應用恢復正常,於是沒做處理。但是後來問題出現頻率越來越多,越來越多的同事開始重複,於是感覺代碼可能有問題,開始排查。

首先發現開發的本地ide沒有發現問題,應用卡死時間數據庫,redis都正常,並且無特殊錯誤日誌。開始懷疑是沙盒環境機器問題(測試環境本身就很脆!_!)

於是ssh上了服務器執行以下命令

最佳

這時發現機器還算正常,但是內心還是?,於是打算看下jvm串行信息

先看下問題應用比較耗資源的線程

執行top -H -p 12798

找到前3個相對比較耗資源的線程

jstack查看堆內存

jstack 12798 | grep 12799的16二進制31ff

沒拋光什麼問題,上下10行也看看遂執行

看到一些線程都是處於鎖定狀態。但沒有出現業務相關的代碼,忽略了。這時候沒有什麼頭緒。思考一番。決定放棄這次卡死狀態的機器

爲了保護事故現場先轉儲問題主機所有堆內存,然後調試模式重啓測試環境應用,打算問題再顯時直接遠程調試問題機器

第二天問題再現,於是通知運維nginx轉發拿掉這臺問題應用,自己遠程調試tomcat。

API等待服務響應,沒進斷點。這時候有點懵逼,冷靜了一會,在入口之前的aop地方下,自己的隨意找了一個接口,斷點在接口入口地方,悲劇開始,什麼也沒有發生!了個斷點,再debug一次,這次進了斷點,f8 N次後發現在執行redis命令的時候卡主了。繼續跟,最後在到jedis的一個地方發現問題:

/**
 * Returns a Jedis instance to be used as a Redis connection. The instance can be newly created or retrieved from a
 * pool.
 * 
 * @return Jedis instance ready for wrapping into a {@link RedisConnection}.
 */
protected Jedis fetchJedisConnector() {
   try {
      if (usePool && pool != null) {
         return pool.getResource();
      }
      Jedis jedis = new Jedis(getShardInfo());
      // force initialization (see Jedis issue #82)
      jedis.connect();
      return jedis;
   } catch (Exception ex) {
      throw new RedisConnectionFailureException("Cannot get Jedis connection", ex);
   }
}

上面pool.getResource()後線程開始wait

public T getResource() {
  try {
    return internalPool.borrowObject();
  } catch (Exception e) {
    throw new JedisConnectionException("Could not get a resource from the pool", e);
  }
}

返回internalPool.borrowObject(); 這個代碼應該是一個租賃的代碼之後跟

public T borrowObject(long borrowMaxWaitMillis) throws Exception {
    this.assertOpen();
    AbandonedConfig ac = this.abandonedConfig;
    if (ac != null && ac.getRemoveAbandonedOnBorrow() && this.getNumIdle() < 2 && this.getNumActive() > this.getMaxTotal() - 3) {
        this.removeAbandoned(ac);
    }

    PooledObject<T> p = null;
    boolean blockWhenExhausted = this.getBlockWhenExhausted();
    long waitTime = 0L;

    while(p == null) {
        boolean create = false;
        if (blockWhenExhausted) {
            p = (PooledObject)this.idleObjects.pollFirst();
            if (p == null) {
                create = true;
                p = this.create();
            }

            if (p == null) {
                if (borrowMaxWaitMillis < 0L) {
                    p = (PooledObject)this.idleObjects.takeFirst();
                } else {
                    waitTime = System.currentTimeMillis();
                    p = (PooledObject)this.idleObjects.pollFirst(borrowMaxWaitMillis, TimeUnit.MILLISECONDS);
                    waitTime = System.currentTimeMillis() - waitTime;
                }
            }

            if (p == null) {
                throw new NoSuchElementException("Timeout waiting for idle object");
            }

其中有段代碼

if (p == null) {
    if (borrowMaxWaitMillis < 0L) {
        p = (PooledObject)this.idleObjects.takeFirst();
    } else {
        waitTime = System.currentTimeMillis();
        p = (PooledObject)this.idleObjects.pollFirst(borrowMaxWaitMillis, TimeUnit.MILLISECONDS);
        waitTime = System.currentTimeMillis() - waitTime;
    }
}

借款MaxWaitMillis <0會一直執行,然後一直循環了開始懷疑這個值沒有配置

找到redis池配置,發現確實沒有配置MaxWaitMillis,配置後else代碼也是一個異常

繼續F8

public E takeFirst() throws InterruptedException {
    this.lock.lock();

    Object var2;
    try {
        Object x;
        while((x = this.unlinkFirst()) == null) {
            this.notEmpty.await();
        }

        var2 = x;
    } finally {
        this.lock.unlock();
    }

    return var2;
}

到這邊發現lockword眼,開始懷疑所有請求api都被分開了了

隨後再次ssh服務器安裝arthas,(Arthas是阿里巴巴開源的Java診斷工具)

執行線程命令

發現大量http-nio的線程等待狀態,http-nio-8083-exec-這個線程其實就是出來http請求的tomcat線程

隨意找一個線程查看堆內存

螺紋-428

這是能確認就是api一直轉圈的問題,就是這個redis獲取連接的代碼導致的,

解釋的線程代碼所有線程都在等@ 53e5504e這個對象釋放鎖。於是jstack上下搜了一把53e5504e,沒有找到這個對象所在線程。

自此。問題原因能確定是redis連接獲取的問題。但是什麼原因造成獲取不到連接的還不能確定

再次執行arthas的thread -b(thread -b,查找當前多個其他線程的線程)

沒有結果。這邊和想的不一樣,應該是能找到一個雙重線程的,於是看了下這個命令的文檔,發現有下面的一句話

好吧,我們剛好是後者。。。 。

修改。重新修改池配置,將獲取連接超時時間設置爲2s,然後等問題再次重現時觀察應用最後正常時幹過什麼。

添加一下配置

JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
.......
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxWaitMillis(2000);
.......
jedisConnectionFactory.afterPropertiesSet();

重啓服務,等待。。。 。

又過一天,再次復現

ssh服務器,檢查tomcat訪問日誌,發現大量api請求出現500,

org.springframework.data.redis.RedisConnectionFailureException:無法獲取Jedis連接。嵌套的異常是redis.clients.jedis.exceptions.JedisConnectionException:無法從org.springframework的org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:140)
的池中獲取資源。org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:57)處的data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:229)在org.springframework.data.redis 處。 core.RedisConnectionUtils.doGetConnection(RedisConnectionUtils.java:128)




在org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:91)
在org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:78)
在org.springframework.data.redis 
org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:152)
上的org.springframework.data.redis.core.AbstractOperations.execute(AbstractOperations )上的.core.RedisTemplate.execute(RedisTemplate.java:177).java:85),
位於org.springframework.data.redis.core.DefaultHashOperations.get(DefaultHashOperations.java:48)

找到源頭第一次出現500地方,

發現以下代碼

.......
Cursor c = stringRedisTemplate.getConnectionFactory().getConnection().scan(options);
while (c.hasNext()) {
.....,,
   }

分析這個代碼,stringRedisTemplate.getConnectionFactory()。getConnection()獲取池中的redisConnection後,並沒有後續操作,則此時redis連接池中的鏈接被租賃後並沒有釋放或退還到鏈接池中,雖然業務已處理完畢redisConnection已經足夠,但是pool中的redisConnection的狀態還沒有回到idle狀態

正常應爲

自此問題已經找到。

總結spring stringRedisTemplate對redis常規操作做了一些封裝,但還不支持像Scan SetNx等命令,這時需要拿到jedis Connection進行一些特殊的命令

使用stringRedisTemplate.getConnectionFactory()。getConnection()是不被推薦的

我們可以使用

stringRedisTemplate.execute(new RedisCallback<Cursor>() {

     @Override
     public Cursor doInRedis(RedisConnection connection) throws DataAccessException {

       return connection.scan(options);
     }
   });

來執行,

或者使用完connection後,用

RedisConnectionUtils.releaseConnection(connfactory);

來釋放連接。

同時,redis中也不建議使用鍵命令,redis pool的配置應該合理配上,否則出現問題無錯誤日誌,無報錯,定位相當困難。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章