首页 > 解决方案 > Spring Boot - 如何检查特定应用程序 URL 的状态 200

问题描述

我在 Spring Boot Admin 下监控了几个应用程序。Spring Boot Admin 非常擅长告诉我应用程序是启动还是关闭以及其他各种指标。

我还想知道这些应用程序公开的某些 URL 正在返回 200 的 HTTP 状态。具体来说,我想每天向这些 URL 发送一次 GET 请求。如果它从其中任何一个接收到非 200 状态,它会发送一封电子邮件,说明哪些 URL 报告非 200。

Spring Boot Admin 可以做些什么吗?我知道 custom HealthIndicator,但不确定它是否可以安排或是否适合。

在我构建自己的应用程序以进行 GET 调用和发送电子邮件之前,我只是想看看 Spring Boot Admin 是否提供了支持这样做的东西。

更新

URL 公开为 Eureka 服务,我通过 Spring Cloud OpenFeign 从其他服务调用服务。

更新 2

我继续构建自己的自定义应用程序来处理这个问题。详细信息如下,但如果 Spring 提供开箱即用的东西来做到这一点,仍然很感兴趣。

应用程序.yml

app:
  serviceUrls: 
    - "http://car-service/cars?category=sedan"
    - "http://truck-service/trucks"
cron: "0 0 10 * * *"

网址被读入:

@Component
@ConfigurationProperties(prefix = "app")
@Getter
@Setter
public class ServiceUrls {
    private String[] serviceUrls;
}

通过 cron,计划每天运行一次:

@Component
@RequiredArgsConstructor
@Slf4j
public class ServiceCheckRunner {
    
    private final ServiceHealth serviceHealth;
    
    @Scheduled(cron = "${cron}")
    public void runCheck() {
        serviceHealth.check();
    }
}

这是检查 URL 是否不返回错误的代码:

@Service
@RequiredArgsConstructor
@Slf4j
public class ServiceHealth {

    private final ServiceUrls serviceUrls;
    private final RestTemplate rest;
    
    public void check() {

        List<String> failedServiceUrls = new ArrayList<>();
        for (String serviceUrl : serviceUrls.getServiceUrls()) {
            try {

                ResponseEntity<String> response = rest.getForEntity(serviceUrl, String.class);
                
                if (!response.getStatusCode().is2xxSuccessful()) {
                    failedServiceUrls.add(serviceUrl);
                }

            } catch (Exception e){
                failedServiceUrls.add(serviceUrl);
            }
            
        }

        // code to send an email with failedServiceUrls.
    }   
}

标签: javaspringspring-bootspring-boot-admin

解决方案


您可以使用 Spring Boot Admin 来在注册客户将其状态从 UP 更改为 OFFLINE 或其他情况时发送电子邮件通知。

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>2.4.0</version>
</dependency>

应用程序属性

spring.mail.host=smtp.example.com
spring.mail.username=smtp_user
spring.mail.password=smtp_password
spring.boot.admin.notify.mail.to=admin@example.com

但是,如果您确实需要每天检查一次客户端状态,则需要实施自定义解决方案。


推荐阅读