java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java后端本地调试

Java后端本地调试实用方法总结大全

作者:廋到被风吹走

这篇文章主要介绍了Java后端本地调试实用方法总结大全的相关资料,每个部分都提供了实用的技巧和工具推荐,帮助开发者提高调试效率,文中介绍的非常详细,需要的朋友可以参考下

一、IDE 调试基础技巧

1.IDEA 断点调试(必备)

核心功能

实用技巧

二、日志与监控

2.SLF4J + Logback 动态日志级别

场景:生产环境无法重启,需动态调整日志排查问题。

配置

# application.yml
logging:
  level:
    root: INFO
    com.example.service: DEBUG
    com.example.mapper: TRACE

动态修改(无需重启):

// 通过 Actuator 端点
@RestController
public class LogController {
    @Autowired
    private LoggingSystem loggingSystem;
    
    @PostMapping("/log/level")
    public void setLogLevel(@RequestParam String logger, @RequestParam String level) {
        loggingSystem.setLogLevel(logger, LogLevel.valueOf(level));
    }
}

访问:POST /actuator/loggers/com.example.service + Body {"configuredLevel": "DEBUG"}

3.Spring Boot Actuator 监控

关键端点

management:
  endpoints:
    web:
      exposure:
        include: health,info,beans,conditions,env,metrics,mappings,loggers

常用调试场景

三、本地环境模拟

4.Docker Compose 一键模拟中间件

docker-compose.yml 示例

version: '3.8'
services:
  mysql:
    image: mysql:8.0
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: test
    volumes:
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
  
  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
  
  kafka:
    image: confluentinc/cp-kafka:latest
    ports:
      - "9092:9092"
    environment:
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
  
  nacos:
    image: nacos/nacos-server:v2.2.3
    ports:
      - "8848:8848"
    environment:
      MODE: standalone

启动命令docker-compose up -d

优势:团队协作环境一致,CI/CD 可直接复用。

5.内存数据库快速测试

场景:单元测试无需连接真实数据库。

// 测试类配置
@SpringBootTest
@TestPropertySource(locations = "classpath:application-test.yml")
public class UserServiceTest {
    // 使用 H2 内存数据库
}

// application-test.yml
spring:
  datasource:
    url: jdbc:h2:mem:testdb
    driver-class-name: org.h2.Driver
  sql:
    init:
      mode: always
      schema-locations: classpath:schema-h2.sql

四、代码增强与热部署

6.Spring Boot DevTools 热部署

配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

特性

7.JRebel 商业热部署(终极方案)

优势真正的热交换,无需重启,支持类结构修改(增删方法、字段)。

使用步骤

  1. 安装 IDEA 插件
  2. 激活许可证
  3. 启动时选择 JRebel Debug
  4. 修改代码后 Ctrl + Shift + F9 编译当前文件即时生效

五、单元测试与 Mock

8.Spring Boot Test 最佳实践

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class UserControllerTest {
    @Autowired
    private MockMvc mockMvc;
    
    @MockBean
    private UserService userService; // 自动注入 Mock 对象
    
    @Test
    void testGetUser() throws Exception {
        // 打桩
        when(userService.getUser(1L)).thenReturn(new User("test"));
        
        mockMvc.perform(get("/api/users/{id}", 1L))
               .andExpect(status().isOk())
               .andExpect(jsonPath("$.name").value("test"));
        
        verify(userService, times(1)).getUser(1L);
    }
}

9.Mock 中间件(Embedded)

@TestConfiguration
public class TestRedisConfig {
    @Bean
    public RedisServer redisServer() {
        return RedisServer.newRedisServer().start(); // 嵌入式 Redis
    }
}

支持组件

六、高级调试技巧

10.远程调试(Remote Debug)

场景:调试部署在测试环境/容器中的应用。

启动 JVM 参数

java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar app.jar

IDEA 配置

  1. Run → Edit Configurations → + Remote JVM Debug
  2. Host: 测试服务器IP Port: 5005
  3. 点击 Debug 图标连接

Docker 中开启

FROM openjdk:17
EXPOSE 5005
CMD ["java", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005", "-jar", "app.jar"]

11.JMX 监控与 JVisualVM

启动参数

-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

JVisualVM 连接jvisualvm → 右键 Local → JMX Connection → localhost:9999

功能

12.Arthas 线上诊断神器

场景:生产环境无法远程调试,需动态诊断。

安装使用

curl -O https://arthas.aliyun.com/arthas-boot.jar
java -jar arthas-boot.jar # 选择 Java 进程

核心命令

七、多线程与异步调试

13.线程 Dump 分析

命令行

# 查看 Java 进程
jps

# 生成线程 Dump
jstack <pid> > thread.dump

在线分析:https://fastthread.io/ 或 https://jstack.review/

关键状态

14.异步任务调试

@Service
public class AsyncService {
    @Async
    public CompletableFuture<User> asyncGetUser(Long id) {
        // 断点会命中,但线程名是 task-1/task-2
        return CompletableFuture.completedFuture(userMapper.selectById(id));
    }
}

IDEA 调试技巧

八、网络与 HTTP 调试

15.MockServer 模拟外部 API

@BeforeEach
void setUp() {
    mockServer = ClientAndServer.startClientAndServer(1080);
    
    // 配置 Mock 响应
    mockServer.when(
        request()
            .withMethod("POST")
            .withPath("/api/payment")
    ).respond(
        response()
            .withStatusCode(200)
            .withBody("{\"status\":\"success\"}")
    );
}

16.Wireshark/TCPDump 抓包分析

# 抓取 8080 端口的 HTTP 请求
sudo tcpdump -i any -w capture.pcap port 8080

# 用 Wireshark 打开分析
wireshark capture.pcap

九、专项调试工具

17.内存溢出(OOM)分析

启动参数保留堆 Dump

-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/path/to/dump.hprof
-XX:+PrintGCDetails
-XX:+PrintGCDateStamps
-Xloggc:/path/to/gc.log

分析工具

18.SQL 调试

MyBatis 日志

logging:
  level:
    com.example.mapper: DEBUG # 打印 SQL 和参数

p6spy 监控

<dependency>
    <groupId>p6spy</groupId>
    <artifactId>p6spy</artifactId>
</dependency>

自动打印 SQL 执行时间,识别慢查询。

十、调试效率提升技巧

19.IDEA 书签与断点技巧

20.Spring Boot 调试模式

# 开启 DEBUG 日志
java -jar app.jar --debug

# 查看自动配置报告
java -jar app.jar --debug > auto-config-report.txt

# 启动时打印 Bean 创建过程
-Dlogging.level.org.springframework.beans.factory=DEBUG

总结:调试方法论

问题类型首选工具备选方案
业务逻辑错误IDEA 断点调试日志 + 单元测试
环境问题Docker ComposeEmbedded 组件
性能问题JVisualVM/ArthasJProfiler(商业)
生产问题Arthas远程 Debug
并发问题jstack + 线程分析JMC(Java Mission Control)
内存泄漏Eclipse MATJProfiler

黄金法则先在单元测试中复现,再用断点/日志定位,最后工具分析。调试是系统性工程,结合多种手段才能事半功倍。

到此这篇关于Java后端本地调试实用方法总结大全的文章就介绍到这了,更多相关Java后端本地调试内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文