Java 远程调试

154 阅读1分钟

Java 远程调试

k8s 部署的 java 应用,如何进行远程调试?

准备环境

  • 本地开发环境:macOS
  • 本地终端: iTerm2+ zsh
  • 本地开发工具:IntelliJ IDEA

1. 添加kubetrl remote debug别名

~/.zshrc 文件中添加以下内容:

kube-log() {
    if [ $# -lt 1 ]
    then
        echo 'kube-log {deploy-name} {other-arguments}'
    else
        kubectl get pods | /usr/bin/grep $1 | awk '{print $1}' | xargs kubectl logs ${*:2}
    fi
}
kube-port-forward() {
  kubectl get svc | /usr/bin/grep $1 | awk '{split($5, array, ":"); print "services/"$1" "array[1]":"array[1]}' | xargs kubectl port-forward
}
kube-remote-debug() {
    if [ $# -lt 1 ]
    then
        echo 'kube-remote-debug {deploy-name} {local-port}(optional)'
    elif [ $# -lt 2 ]
    then
        local DEPLOY_NAME=$1
        local LOCAL_PORT='5005'
        kubectl get pod | /usr/bin/grep $DEPLOY_NAME | awk '{print $1}' | xargs -I {} kubectl port-forward pod/{} $LOCAL_PORT:5005
    else
        local DEPLOY_NAME=$1
        local LOCAL_PORT=$2
        kubectl get pod | /usr/bin/grep $DEPLOY_NAME | awk '{print $1}' | xargs -I {} kubectl port-forward pod/{} $LOCAL_PORT:5005
    fi
}

注意:

  1. 当前配置的 kube-remote-debug 命令,默认将本地端口映射到5005,也可以做自定义映射。
  2. 修改完配置文件后,需要重新加载配置文件:source ~/.zshrc

2. 启动远程调试服务

执行 kube-remote-debug {deploy-name} port,如:kube-remote-debug tmc-service 5005。 端口要与第一步终配置的端口一致。 看到如下结果,则启动成功:

Forwarding from 127.0.0.1:5005 -> 5005
Forwarding from [::1]:5005 -> 5005
Handling connection for 5005

3. 配置IDEA

  1. 打开IDEA,点击 Run -> Edit Configurations... -> + -> Remote JVM Debug
  2. Name: 自定义,如:remote-debug
  3. 填写 HostPort,端口为 5005, 与第一步终配置的端口一致。
  4. Use Module Classpath: 勾选上远程服务对应的moudle
  5. 点击 OK 完成配置
  6. 点击 Debug,启动远程调试,看到Console中输出如下内容,则启动成功:
  Connected to the target VM, address: '127.0.0.1:5005', transport: 'socket'
  Disconnected from the target VM, address: '127.0.0.1:5005', transport: 'socket'