使用Arthas 获取Spring ApplicationContext还原问题现场

背景

最近来了个实习僧小弟,安排他实现对目标网站 连通性检测的小功能,简单讲就是将下边的shell 脚本换成Java 代码来实现web

#!/bin/bash
URL="https://www.baidu"
HTTP_CODE=`curl -o /dev/null -s -w "%{http_code}" "${URL}"`
#echo $HTTP_CODE
if [ $HTTP_CODE != '200' ];then
curl 'https://oapi.dingtalk.com/robot/send?access_token=xx' \
   -H 'Content-Type: application/json' \
   -d '{"msgtype": "text",
        "text": {
             "content": "百度平台状态不正常,请注意!"
        },
        "isAtAll": true
      }'

fi

功能实现

使用spring task

@Scheduled(cron = "0 0 0/1 * * ? ")
public void startSchedule() {
    log.info("开始执行定时任务 ,检测百度网站连通性");
    try {
        HttpResponse response = HttpRequest.get("").execute();
        if (HttpStatus.HTTP_OK != response.getStatus()) {
            this.send2DingTalk(response.getStatus());
        }
        log.info("请求百度成功,返回报文:{}",response.body());
    } catch (HttpException e) {
        log.error("请求异常百度:{}", e);
        this.send2DingTalk(e.getMessage());
    }
    log.info("执行检测百度网站连通任务完毕");
}

问题描述

部署在服务器上,个人老jio本 都已经呼叫任务状态不正常了,但是小弟的Java 代码仍是没有执行通知spring

  • 去翻生产日志,只输入了开始并无输出定时任务结束,感受是哪里卡死,想固然觉得若是超时总会到catch 逻辑,排查无果
  • 因为任务是一小时一次,如何快速触发一下这个异常,还原事故现场
  • 因为使用简单的Spring Task 没有图形化界面和API接口

Arthas 还原事故现场,从新触发任务

核心拿到 spring context 而后执行它的 startSchedule 方法shell

肯定监控点

  • SpringMVC 的请求会经过 RequestMappingHandlerAdapter 执行invokeHandlerMethod 到达目标接口上进行处理
  • 而在 RequestMappingHandlerAdapter类中有 getApplicationContext()
@Nullable
public final ApplicationContext getApplicationContext() throws IllegalStateException {
    if (this.applicationContext == null && this.isContextRequired()) {
        throw new IllegalStateException("ApplicationObjectSupport instance [" + this + "] does not run in an ApplicationContext");
    } else {
        return this.applicationContext;
    }
}
  • 任意执行一次请求获取到 RequestMappingHandlerAdapter target 目标,而后执行 getApplicationContext

tt命令 获取到ApplicationContext

  • arthas 执行 tt
tt -t org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter invokeHandlerMethod
  • 任意执行一次web 请求,tt 便可捕获
    json

  • 根据目标的索引,执行自定义 OGNL 表达式便可api

tt -i 1019 -w 'target.getApplicationContext()'

使用ApplicationContext获取 定时任务bean 执行 startSchedule

tt -i 1000 -w 'target.getApplicationContext().getBean("baiduSchedule").startSchedule()'

ok 任务从新触发了bash

事故缘由调查清楚,因为使用hutool 的工具类 没有设置timeout 致使无限等待,因此没有执行catch 逻辑服务器

总结

相关文章
相关标签/搜索