我正在探索激活 SpringBoot 1.X 的就绪性和活性探针的选项。必须启用两个端点才能实现无缝 Kubernetes 部署。关于实现这一目标有什么见解吗?
/actuator/health/liveness
/actuator/health/readiness
在即将推出的 Spring 版本中获得这些功能是否可行,还是我应该继续自己实现它们?
提前致谢。
对于 Spring Boot 1.X,您不会立即拥有这些端点。但是,您可以实现自定义运行状况检查端点来实现类似的功能。
创建自定义健康指标:通过扩展Spring Boot提供的HealthIndicator接口来实现自定义健康指标。您可以编写逻辑来确定应用程序不同组件的健康状态。
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class CustomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
// Logic to check the health of your application
if (isApplicationHealthy()) {
return Health.up().build();
} else {
return Health.down().build();
}
}
private boolean isApplicationHealthy() {
// Check the health of your application components
return true; // Return true if the application is healthy, false otherwise
}
}
公开自定义端点:公开应用程序控制器中的自定义端点以公开健康状态信息。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HealthCheckController {
@Autowired
private CustomHealthIndicator customHealthIndicator;
@GetMapping("/custom/health/liveness")
public Health liveness() {
return customHealthIndicator.health();
}
@GetMapping("/custom/health/readiness")
public Health readiness() {
return customHealthIndicator.health();
}
}
在 Kubernetes 中配置探针:实现这些端点后,您可以配置 Kubernetes 以在部署配置中使用它们进行就绪性和活动性探针。
apiVersion: apps/v1
kind: Deployment
metadata:
name: your-app
spec:
replicas: 1
selector:
matchLabels:
app: your-app
template:
metadata:
labels:
app: your-app
spec:
containers:
- name: your-app
image: your-app-image:tag
ports:
- containerPort: 8080
readinessProbe:
httpGet:
path: /custom/health/readiness
port: 8080
livenessProbe:
httpGet:
path: /custom/health/liveness
port: 8080