关于java:同事乱用-Redis-卡爆我真是醉了

9次阅读

共计 5818 个字符,预计需要花费 15 分钟才能阅读完成。

起源:https://my.oschina.net/xiaomu…

首先说下问题景象:内网 sandbox 环境 API 继续 1 周呈现利用卡死,所有 api 无响应景象

刚开始当测试埋怨环境响应慢的时候,咱们重启一下利用,利用恢复正常,于是没做解决。

然而起初问题呈现频率越来越频繁,越来越多的共事开始埋怨,于是感觉代码可能有问题,开始排查。

首先发现开发的本地 ide 没有发现问题,利用卡死时候数据库,redis 都失常,并且无非凡谬误日志。开始狐疑是 sandbox 环境机器问题(测试环境自身就很脆!_!)

于是 ssh 上了服务器 执行以下命令

top

这时发现机器还算失常,于是打算看下 jvm 堆栈信息

先看下问题利用比拟耗资源的线程

执行 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 命令的时候卡主了。

另外,Redis 系列面试题和答案全副整顿好了,微信搜寻​Java 技术栈,在后盾发送:面试,​能够在线浏览。

持续跟,最初在到 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);
  }
}

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 会始终执行,而后始终循环了 开始狐疑这个值没有配置

找到 redis pool 配置,发现的确没有配置 MaxWaitMillis,配置后 else 代码也是一个 Exception 并不能解决问题

持续 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;
}

到这边 发现 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, 而后等问题再次复现时察看利用最初失常时干过什么。

增加一下配置

JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
.......
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxWaitMillis(2000);
.......
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()

是不被举荐的

咱们能够应用

stringRedisTemplate.execute(new RedisCallback() {

     @Override
     public Cursor doInRedis(RedisConnection connection) throws DataAccessException {return connection.scan(options);
     }

});

来执行,或者应用完 connection 后,用

RedisConnectionUtils.releaseConnection(conn, factory);

来开释 connection.

同时,redis 中也不倡议应用 keys 命令,redis pool 的配置应该正当配上,否则呈现问题无谬误日志,无报错,定位相当艰难。

近期热文举荐:

1.1,000+ 道 Java 面试题及答案整顿 (2021 最新版)

2. 别在再满屏的 if/ else 了,试试策略模式,真香!!

3. 卧槽!Java 中的 xx ≠ null 是什么新语法?

4.Spring Boot 2.5 重磅公布,光明模式太炸了!

5.《Java 开发手册(嵩山版)》最新公布,速速下载!

感觉不错,别忘了顺手点赞 + 转发哦!

正文完
 0