如何对线上项目Debug
说明:本文介绍如何使用IDEA中的 Remote JVM Debug 功能对线上运行的项目Debug。
创建项目
创建一个测试项目,只有一个接口,该接口有一个BUG,如下:
(controller接口)
import com.hezy.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@Autowiredprivate HelloService helloService;@GetMapping("/hello")public String hello() {return helloService.printInfo();}
}
(service实现类,手动制造了一个BUG)
import com.hezy.service.HelloService;
import org.springframework.stereotype.Service;@Service
public class HelloServiceImpl implements HelloService {@Overridepublic String printInfo() {return print();}/*** 定义一个输出信息的方法*/public String print() {// 打印100个数字for (int i = 0; i < 100; i++) {System.out.println(i);}// 手动制造一个异常int i = 1 / 0;return "Hello World!";}
}
假设这个BUG我们没发现(嘿嘿),代码被我们推到测试环境跑,然后无意间调用该接口报错;
又假设这个BUG在本地无法复现,只有在线上环境才会出现,这时我们看着一堆日志无法排查;
远程Debug
进入正题,针对上面的情况,我们可以考虑使用IDEA的远程Debug功能,如下:
(1)新增远程Debug应用
进入Configuration
窗口
新增一个启动项,选择Remote JVM Debug
,即远程Debug
设置相关信息,端口号使用默认的5005即可,如有需要,可手动修改。另外注意一下JDK版本;
(2)线上项目Debug启动
另外,线上的项目需要Debug启动,如果是脚本或者命令行的方式启动的,可在对应的jar前面加上下面这行配置:
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005
注意上面这行配置是在前面的配置窗口里中拷贝过来的,不要手敲:
(3)Debug启动
启动服务器上面的项目,可以看到首行有监听5005端口的信息:
在项目中启动远程Debug程序,没有报错,另外可以看到打的断点都卡住了。
这时,再调用一下线上项目的接口,断点进入到本地IDEA中了:
非常Nice,这时就可以排查问题了。
总结
本文介绍了如何使用IDEA中的Remote JVM Debug
功能对线上的项目进行Debug,排查BUG。本文案例在个人的云服务器上演示,大家操作,需要注意开放相关接口(8080、5005)。