Skip to content

Commit

Permalink
Merge pull request #22 from frankliu20/frank/reliable-java-9-10
Browse files Browse the repository at this point in the history
feat: add sample to define health probe with spring-acutator
  • Loading branch information
frankliu20 authored Sep 10, 2024
2 parents 36896c4 + 1fefc48 commit 467c57e
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
5 changes: 5 additions & 0 deletions config/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ spring.cloud.refresh.refreshable: false
# Logging
logging.level.org.springframework: INFO

# enable health probes
management.health.livenessState.enabled: true
management.health.readinessState.enabled: true
management.endpoint.health.probes.enabled: true

# Metrics
management:
endpoint:
Expand Down
5 changes: 5 additions & 0 deletions docs/02_lab_migrate/0203_application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ spring.cloud.refresh.refreshable: false
# Logging
logging.level.org.springframework: INFO

# enable health probes
management.health.livenessState.enabled: true
management.health.readinessState.enabled: true
management.endpoint.health.probes.enabled: true

# Metrics
management:
endpoint:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package org.springframework.samples.petclinic.customers.health;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.samples.petclinic.customers.model.OwnerRepository;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class ServiceHealthIndicator implements HealthIndicator {

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private boolean isHealthy = false;

private OwnerRepository ownerRepo;

public ServiceHealthIndicator(OwnerRepository ownerRepo) {
this.ownerRepo = ownerRepo;
scheduler.scheduleAtFixedRate(() -> {
checkDatabaseStatus();
if (isHealthy) {
scheduler.shutdown();
}
}, 10, 5, TimeUnit.SECONDS);
}

private void checkDatabaseStatus() {
boolean databaseReady = ownerRepo.findAll().size() > 0;
if (databaseReady) {
isHealthy = true;
log.info("Database is healthy. Stopping checks.");
} else {
log.info("Database is not healthy. Checking again in 5 seconds.");
}
}

@Override
public Health health() {
return isHealthy ? Health.up().build() : Health.down().build();
}
}

0 comments on commit 467c57e

Please sign in to comment.