1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

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

        共 11113字,需瀏覽 23分鐘

         ·

        2021-07-04 14:50

        首先說下問題現象:內網sandbox環(huán)境API持續(xù)1周出現應用卡死,所有api無響應現象

        剛開始當測試抱怨環(huán)境響應慢的時候 ,我們重啟一下應用,應用恢復正常,于是沒做處理。

        但是后來問題出現頻率越來越頻繁,越來越多的同事開始抱怨,于是感覺代碼可能有問題,開始排查。

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

        于是ssh上了服務器 執(zhí)行以下命令

        top

        這時發(fā)現機器還算正常,于是打算看下jvm 堆棧信息

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

        執(zhí)行 top -H -p 12798

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

        jstack 查看堆內存

        jstack 12798 |grep 1279916進制 31ff

        沒看出什么問題,上下10行也看看,于是執(zhí)行

        看到一些線程都是處于lock狀態(tài)。但沒有出現業(yè)務相關的代碼,忽略了。這時候沒有什么頭緒。思考一番。決定放棄這次卡死狀態(tài)的機器

        為了保護事故現場 先 dump了問題進程所有堆內存,然后debug模式重啟測試環(huán)境應用,打算問題再顯時直接遠程debug問題機器

        第二天問題再現,于是通知運維nginx轉發(fā)拿掉這臺問題應用,自己遠程debug tomcat。

        自己隨意找了一個接口,斷點在接口入口地方,悲劇開始,什么也沒有發(fā)生!API等待服務響應,沒進斷點。

        這時候有點懵逼,冷靜了一會,在入口之前的aop地方下了個斷點,再debug一次,這次進了斷點,f8 N次后發(fā)現在執(zhí)行redis命令的時候卡主了。

        繼續(xù)跟,最后在到jedis的一個地方發(fā)現問題:

        /**
         * 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);
          }
        }

        return 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 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;
            }
        }

        borrowMaxWaitMillis<0會一直執(zhí)行,然后一直循環(huán)了 開始懷疑這個值沒有配置

        找到redis pool配置,發(fā)現確實沒有配置MaxWaitMillis,配置后else代碼也是一個Exception 并不能解決問題

        繼續(xù)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;
        }

        到這邊 發(fā)現lock字眼,開始懷疑所有請求api都被阻塞了

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

        執(zhí)行thread命令

        發(fā)現大量http-nio的線程waiting狀態(tài),http-nio-8083-exec-這個線程其實就是出來http請求的tomcat線程

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

        thread -428

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

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

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

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

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

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

        再次整理下思路。這次修改redis pool 配置,將獲取連接超時時間設置為2s,然后等問題再次復現時觀察應用最后正常時干過什么。

        添加一下配置

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

        重啟服務,等待。。。。

        又過一天,再次復現

        ssh 服務器,檢查tomcat accesslog ,發(fā)現大量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地方,

        發(fā)現以下代碼

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

        分析這個代碼,stringRedisTemplate.getConnectionFactory().getConnection()獲取pool中的redisConnection后,并沒有后續(xù)操作

        也就是說此時redis 連接池中的鏈接被租賃后并沒有釋放或者退還到鏈接池中,雖然業(yè)務已處理完畢 redisConnection 已經空閑,但是pool中的redisConnection的狀態(tài)還沒有回到idle狀態(tài)

        正常應為

        自此問題已經找到。

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

        使用

        stringRedisTemplate.getConnectionFactory().getConnection()

        是不被推薦的

        我們可以使用

        stringRedisTemplate.execute(new RedisCallback() {

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

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

        來執(zhí)行,或者使用完connection后 ,用

        RedisConnectionUtils.releaseConnection(conn, factory);

        來釋放connection.

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

        作者:小木-_-

        來源:

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

        本文版權歸作者所有


        END


        順便給大家推薦一個GitHub項目,這個 GitHub 整理了上千本常用技術PDF,絕大部分核心的技術書籍都可以在這里找到,

        GitHub地址:https://github.com/javadevbooks/books

        Gitee地址:https://gitee.com/javadevbooks/books

        電子書已經更新好了,你們需要的可以自行下載了,記得點一個star,持續(xù)更新中..




        瀏覽 41
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            男女拍拍视频免费 | 中文字幕精品一区二区精品绿巨人 | 五月天综合激情网 | 一级A黄片 | 91福利在线观看视频 | 久久久精品呻吟 | 男男被各种姿势c到高潮高h | 人人看片人人看特色大片 | 91网站美女被草畜白浆视频 | 日本一本bbw少妇 |