添加ACTUATOR依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

配置文件增加

management.endpoint.health.probes.enabled=true

访问
/actuator/health/liveness 和 /actuator/health/readiness 接口会看到返回{“status”:“UP”},并且接口返回200 在非监控状态下会返回50X的状态,正好给K8S使用

自定义修改liveness的状态

有时候有些特殊的资源需要手动修改liveness的状态,可以用如下方法

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.availability.ApplicationAvailability;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.boot.availability.LivenessState;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ThreadLocalRandom;

/**
* @description: TODO
* @author zhoukai
* @date 2022/8/24 19:13
* @version 1.0
*/
@Component
public class CustomChangeLivenessStatus {

    @Autowired
    private ApplicationAvailability applicationAvailability;
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @PostConstruct
    public void init() throws Exception {
        new Thread(){
            @Override
            public void run() {
                try {
                    Thread.sleep(1000*10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                AvailabilityChangeEvent.publish(eventPublisher, applicationAvailability, LivenessState.BROKEN); //主要是这里就是修改状态为DOWN的
            }
        }.start();;
    }
}
Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐