【轉載】記一次因 Redis 使用不當致使應用卡死 bug 的排查及解決!

說明:此篇文章 做者分析問題的思路很好,值得學習記錄,原文轉載自公衆號。java

 

首先說下問題現象:內網sandbox環境API持續1周出現應用卡死,全部api無響應現象nginx

剛開始當測試抱怨環境響應慢的時候 ,咱們重啓一下應用,應用恢復正常,因而沒作處理。redis

可是後來問題出現頻率愈來愈頻繁,愈來愈多的同事開始抱怨,因而感受代碼可能有問題,開始排查。spring

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

因而ssh上了服務器 執行如下命令api

toptomcat

 

這時發現機器還算正常,因而打算看下jvm 堆棧信息服務器

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

執行 top -H -p 12798運維

 

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

jstack 查看堆內存

jstack 12798 |grep 12799的16進制 31ff

 

沒看出什麼問題,上下10行也看看,因而執行

 

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

爲了保護事故現場 先 dump了問題進程全部堆內存,而後debug模式重啓測試環境應用,打算問題再顯時直接遠程debug問題機器

次日問題再現,因而通知運維nginx轉發拿掉這臺問題應用,本身遠程debug tomcat。

本身隨意找了一個接口,斷點在接口入口地方,悲劇開始,什麼也沒有發生!API等待服務響應,沒進斷點。

這時候有點懵逼,冷靜了一會,在入口以前的aop地方下了個斷點,再debug一次,此次進了斷點,f8 N次後發如今執行redis命令的時候卡主了。

繼續跟,最後在到jedis的一個地方發現問題:

 1 /**
 2  * Returns a Jedis instance to be used as a Redis connection. The instance can be newly created or retrieved from a
 3  * pool.
 4  * 
 5  * @return Jedis instance ready for wrapping into a {@link RedisConnection}.
 6  */
 7 protected Jedis fetchJedisConnector() {
 8    try {
 9       if (usePool && pool != null) {
10          return pool.getResource();
11       }
12       Jedis jedis = new Jedis(getShardInfo());
13       // force initialization (see Jedis issue #82)
14       jedis.connect();
15       return jedis;
16    } catch (Exception ex) {
17       throw new RedisConnectionFailureException("Cannot get Jedis connection", ex);
18    }
19 }

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

 1 public T getResource() {
 2   try {
 3     return internalPool.borrowObject();
 4   } catch (Exception e) {
 5     throw new JedisConnectionException("Could not get a resource from the pool", e);
 6   }
 7 }
 8 
 9 return internalPool.borrowObject(); 這個代碼應該是一個租賃的代碼,接着跟
10 
11 public T borrowObject(long borrowMaxWaitMillis) throws Exception {
12     this.assertOpen();
13     AbandonedConfig ac = this.abandonedConfig;
14     if (ac != null && ac.getRemoveAbandonedOnBorrow() && this.getNumIdle() < 2 && this.getNumActive() > this.getMaxTotal() - 3) {
15         this.removeAbandoned(ac);
16     }
17 
18     PooledObject p = null;
19     boolean blockWhenExhausted = this.getBlockWhenExhausted();
20     long waitTime = 0L;
21 
22     while(p == null) {
23         boolean create = false;
24         if (blockWhenExhausted) {
25             p = (PooledObject)this.idleObjects.pollFirst();
26             if (p == null) {
27                 create = true;
28                 p = this.create();
29             }
30 
31             if (p == null) {
32                 if (borrowMaxWaitMillis < 0L) {
33                     p = (PooledObject)this.idleObjects.takeFirst();
34                 } else {
35                     waitTime = System.currentTimeMillis();
36                     p = (PooledObject)this.idleObjects.pollFirst(borrowMaxWaitMillis, TimeUnit.MILLISECONDS);
37                     waitTime = System.currentTimeMillis() - waitTime;
38                 }
39             }
40 
41             if (p == null) {
42                 throw new NoSuchElementException("Timeout waiting for idle object");
43             }

其中有段代碼

1 if (p == null) {
2     if (borrowMaxWaitMillis < 0L) {
3         p = (PooledObject)this.idleObjects.takeFirst();
4     } else {
5         waitTime = System.currentTimeMillis();
6         p = (PooledObject)this.idleObjects.pollFirst(borrowMaxWaitMillis, TimeUnit.MILLISECONDS);
7         waitTime = System.currentTimeMillis() - waitTime;
8     }
9 }

borrowMaxWaitMillis<0會一直執行,而後一直循環了 開始懷疑這個值沒有配置

找到redis pool配置,發現確實沒有配置MaxWaitMillis,配置後else代碼也是一個Exception 並不能解決問題

繼續F8

 1 public E takeFirst() throws InterruptedException {
 2     this.lock.lock();
 3 
 4     Object var2;
 5     try {
 6         Object x;
 7         while((x = this.unlinkFirst()) == null) {
 8             this.notEmpty.await();
 9         }
10 
11         var2 = x;
12     } finally {
13         this.lock.unlock();
14     }
15 
16     return var2;
17 }

到這邊 發現lock字眼,開始懷疑全部請求api都被阻塞了

因而再次ssh 服務器 安裝 arthas ,(Arthas 是Alibaba開源的Java診斷工具)

執行thread命令

 

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

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

thread -428

 

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

解讀這段內存代碼  全部線程都在等 @53e5504e這個對象釋放鎖。因而jstack 全局搜了一把53e5504e ,沒有找到這個對象所在線程。

自此。問題緣由能肯定是 redis鏈接獲取的問題。可是什麼緣由形成獲取不到鏈接的還不能肯定

再次執行 arthas 的thread -b (thread -b, 找出當前阻塞其餘線程的線程)

 

沒有結果。這邊和想的不同,應該是能找到一個阻塞線程的,因而看了下這個命令的文檔,發現有下面的一句話

 

好吧,咱們恰好是後者。。。。

再次整理下思路。此次修改redis pool 配置,將獲取鏈接超時時間設置爲2s,而後等問題再次復現時觀察應用最後正常時幹過什麼。

添加一下配置

1 JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
2 .......
3 JedisPoolConfig config = new JedisPoolConfig();
4 config.setMaxWaitMillis(2000);
5 .......
6 jedisConnectionFactory.afterPropertiesSet();

重啓服務,等待。。。。

又過一天,再次復現

ssh 服務器,檢查tomcat accesslog ,發現大量api 請求出現500,

org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource fr
om the pool
    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:140)
    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:229)
    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:57)
    at org.springframework.data.redis.core.RedisConnectionUtils.doGetConnection(RedisConnectionUtils.java:128)
    at org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:91)
    at org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:78)
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:177)
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:152)
    at org.springframework.data.redis.core.AbstractOperations.execute(AbstractOperations.java:85)
    at org.springframework.data.redis.core.DefaultHashOperations.get(DefaultHashOperations.java:48)

 

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

發現如下代碼

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

分析這個代碼,stringRedisTemplate.getConnectionFactory().getConnection()獲取pool中的redisConnection後,並無後續操做

也就是說此時redis 鏈接池中的連接被租賃後並無釋放或者退還到連接池中,雖然業務已處理完畢 redisConnection 已經空閒,可是pool中的redisConnection的狀態尚未回到idle狀態

 

正常應爲

 

自此問題已經找到。

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

使用

stringRedisTemplate.getConnectionFactory().getConnection()

是不被推薦的

咱們可使用

1 stringRedisTemplate.execute(new RedisCallback() {
2 
3      @Override
4      public Cursor doInRedis(RedisConnection connection) throws DataAccessException {
5 
6        return connection.scan(options);
7      }
8    });

 

來執行,或者使用完connection後 ,用

RedisConnectionUtils.releaseConnection(conn, factory);

來釋放connection.

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

 

【轉載說明】

做者:小木-_-

來源:https://my.oschina.net/xiaomu0082/blog/2990388

相關文章
相關標籤/搜索