并行执行Spring Boot / actuator / heath运行检查

问题描述 投票:1回答:1

我对/ actuator /运行状况检查有几项自定义检查。其中一些调用其他服务以查看它们是否可访问。不幸的是,这可能需要一些时间。因此,我希望Spring Boot可以并行进行这些检查。

演示:

@Component
public class HealthCheck1 extends AbstractHealthIndicator {
    @Override
    protected void doHealthCheck(Health.Builder builder) throws InterruptedException {
        Thread.sleep(5000); // actually make a service call
        builder.up();
    }
}

@Component
public class HealthCheck2 extends AbstractHealthIndicator {
    @Override
    protected void doHealthCheck(Health.Builder builder) throws InterruptedException {
        Thread.sleep(5000); // actually make a service call
        builder.up();
    }
}
$ time http localhost:8080/actuator/health
HTTP/1.1 200 
Connection: keep-alive
Content-Type: application/vnd.spring-boot.actuator.v3+json
Date: Fri, 03 Jan 2020 14:54:31 GMT
Keep-Alive: timeout=60
Transfer-Encoding: chunked

{
    "components": {
        "diskSpace": {
            "details": {
                "free": 398020632576,
                "threshold": 10485760,
                "total": 499963174912
            },
            "status": "UP"
        },
        "healthCheck1": {
            "status": "UP"
        },
        "healthCheck2": {
            "status": "UP"
        },
        "ping": {
            "status": "UP"
        }
    },
    "status": "UP"
}


real    0m10.359s
user    0m0.242s
sys 0m0.036s

这表明当前按顺序进行检查。有办法改变吗?

java spring spring-boot spring-boot-actuator
1个回答
0
投票

由于如@Roland Weisleder在评论中指出的那样,当前实际上不可能并行运行所有运行状况检查,因此您可以执行以下解决方法:

而不是在HealthCheck1中进行实际检查:

  1. 创建另一个进行长时间检查的bean
  2. 定期在某个线程中运行它(使用@ Scheduled,Scheduled Executor或其他工具)
  3. 使它在一个字段中本地存储一个决定,这里没有多线程访问,那个bean是单例,所以您应该很好。
  4. 将该bean注入HealthCheck并获取状态。
@Component
public class MyCustomBeanCheck {
   private boolean isOk;

   // run periodically
   public void doCheck() {
       isOk = contactServiceTakesALongTime();
   }

   public boolean isOk() {
      return isOk;
   }
}

public class HealthCheck1 extends AbstractHealthIndicator {

    private MyCustomBeanCheck myCustomBeanCheck;

    protected void doHealthCheck(Health.Builder builder) throws InterruptedException {
       if(myCustomBeanCheck.isOk()) { // immediate access
         builder.up();
       } else {
         builder.down();
       }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.