1. 搭建Spring Boot项目并实现健康检查接口
从零到可访问:Spring Boot 健康检查接口
本案例的目标是创建一个最小可运行的 Spring Boot 项目,并暴露一个 HTTP 接口返回服务状态。项目使用 Maven 构建,通过 Spring Initializr 生成骨架,最终用 curl 或浏览器验证接口可访问。
项目骨架与依赖选择
在 Spring Initializr(start.spring.io)上做如下选择:
- Project:Maven
- Language:Java
- Spring Boot:3.x(选择当前稳定版,如 3.2.x)
- Group:
com.example - Artifact:
health-demo - Packaging:Jar
- Java:17 或 21(与 Spring Boot 3.x 要求一致)
- Dependencies:Spring Web
生成后解压,得到标准 Maven 目录结构。核心文件是 pom.xml 和 src/main/java/com/example/healthdemo/HealthDemoApplication.java。
关键代码
启动类由 Initializr 自动生成,无需修改:
package com.example.healthdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HealthDemoApplication {
public static void main(String[] args) {
SpringApplication.run(HealthDemoApplication.class, args);
}
}
新增一个控制器类 HealthController.java,放在与启动类相同的包或子包下:
package com.example.healthdemo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
@RestController
public class HealthController {
@GetMapping("/health")
public Map<String, Object> health() {
Map<String, Object> body = new LinkedHashMap<>();
body.put("status", "UP");
body.put("service", "health-demo");
body.put("timestamp", Instant.now().toString());
return body;
}
}
这里使用 @RestController 将类标记为 REST 控制器,@GetMapping("/health") 把 GET 请求映射到 health() 方法。返回 Map 时,Spring 会自动用 Jackson 序列化为 JSON。
启动与验证
在项目根目录执行:
./mvnw spring-boot:run
Windows 下使用 mvnw.cmd spring-boot:run。控制台出现 Tomcat started on port 8080 和 Started HealthDemoApplication 即表示启动成功。
另开终端验证接口:
curl -i http://localhost:8080/health
预期响应:
HTTP/1.1 200
Content-Type: application/json
{"status":"UP","service":"health-demo","timestamp":"2025-01-01T00:00:00Z"}
若返回 404,检查控制器是否在启动类的同级或子包下;若端口被占用,可在 application.properties 中设置 server.port=8081。
验证通过标准:启动无异常,
curl -i http://localhost:8080/health 返回 HTTP 200,响应体 JSON 中 status 为 "UP"。若返回 404,优先检查 HealthController 是否位于启动类所在包或其子包下。