Spring Boot Admin 自定义健康检查

添加自定义类:

 

/**
 * 监控接口的健康情况
 *
 */
@Component
public class ApiHealthIndicator implements HealthIndicator {
 
    @Override
    public Health health() {
        Map<String, String> detailMap = new HashMap<>(); 
        String hisApiUrl = "http://www.baidu.com";
        int hisApiCode = testUrlConnection(hisApiUrl); // perform some specific health check 
        if (hisApiCode != 200) { 
            detailMap.put("HIS Api", "无法访问  " + hisApiUrl);
        } 
        if (detailMap.size() > 0) {
            return Health.down().withDetails(detailMap).build();
        }
        return Health.up().build();
    }

    public int testUrlConnection(String address) {
        int status = 404;
        try {
            URL urlObj = new URL(address);
            HttpURLConnection oc = (HttpURLConnection) urlObj.openConnection();
            oc.setUseCaches(false);
            oc.setConnectTimeout(3000); // 设置超时时间
            status = oc.getResponseCode();// 请求状态
            if (200 == status) {
                // 200是请求地址顺利连通。。
                return status;
            }
        } catch (Exception e) {
            //e.printStackTrace();
            return status;
        }
        return status;
    }
}

 

 

 

posted @ 2021-10-11 18:59  VipSoft  阅读(546)  评论(0编辑  收藏  举报