Spring Boot 将状态记录到数据库Sping Boot admin

pdkcd3nj  于 2023-08-04  发布在  Spring
关注(0)|答案(1)|浏览(116)

有人遇到过需要记录springboot acutator的响应吗?我想使用一个springboot管理服务器,它将查询应用程序并记录每个/health请求对应用程序的响应,并将其写入数据库。
我在谷歌上搜索了我的问题,但什么也没找到。
管理员服务器有应用程序x1c 0d1x的URL,我可以从管理员服务器获取此URL以进行休息请求吗?

kgsdhlau

kgsdhlau1#

可以记录Sping Boot Actuator端点(包括/health端点)的响应,然后使用Spring Boot Admin Server将其写入数据库。Sping Boot Actuator提供了几个端点,允许您监视和管理应用程序,/health端点是其中之一,用于检查应用程序的健康状态。

// Step 1: Set up Spring Boot Admin Server
@SpringBootApplication
@EnableAdminServer
public class AdminServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(AdminServerApplication.class, args);
    }
}

字符串
在上面的示例中,您已经设置了Sping Boot 管理服务器。现在需要配置要监视的客户端应用程序。

// Step 2: Configure Actuator for Remote Applications
@SpringBootApplication
public class MonitoredApplication {
    public static void main(String[] args) {
        SpringApplication.run(MonitoredApplication.class, args);
    }
}


现在,通过实现自定义运行状况指示器来自定义/health响应:

@Component
public class CustomHealthIndicator implements HealthIndicator {
    @Override
    public Health health() {
        // Implement your custom health checks here
        // You can include application-specific information in the Health status
        return Health.up().withDetail("custom", "Custom health check passed").build();
    }
}


最后,在Sping Boot Admin Server应用程序中,实现查询被监视应用程序的/health端点并记录响应的逻辑:

@Service
public class HealthLoggingService {
    private RestTemplate restTemplate = new RestTemplate();

    public void logHealthFromApplication(String applicationUrl) {
        ResponseEntity<Map> response = restTemplate.exchange(
            applicationUrl + "/actuator/health", HttpMethod.GET, null, Map.class);
        
        // Extract relevant information from the response and store it in the database
        // For example, you can log the response status, details, timestamp, etc.
        // You can also parse the JSON response to extract specific data you want to log.
        Map<String, Object> healthDetails = response.getBody();
        // Store the details in the database
    }
}

相关问题