Spring Boot - 如何检查特定应用程序 URL 的状态 200

问题描述

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

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

Spring Boot Admin 能做些什么?我知道自定义 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.
    }   
}

解决方法

您可以使用 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>

application.properties

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...