官术网_书友最值得收藏!

Adding a custom health module

Adding a new custom module to the Spring Boot application is not so complex. For demonstrating this feature, assume that if a service gets more than two transactions in a minute, then the server status will be set as Out of Service.

In order to customize this, we have to implement the HealthIndicator interface, and override the health method. The following code is a quick and dirty implementation to do the job:

    class TPSCounter {
LongAdder count;
int threshold = 2;
Calendar expiry = null;

TPSCounter(){
this.count = new LongAdder();
this.expiry = Calendar.getInstance();
this.expiry.add(Calendar.MINUTE, 1);
}

boolean isExpired(){
return Calendar.getInstance().after(expiry);
}

boolean isWeak(){
return (count.intValue() > threshold);
}

void increment(){
count.increment();
}
}

The preceding code is a simple Plain Old Java Object (POJO) class, which maintains the transaction counts window. The isWeak method checks whether the transaction in a particular window has reached its threshold. isExpired checks whether the current window is expired or not. The increment method simply increases the counter value.

As the next step, implement our custom health indicator class, TPSHealth. This is done by extending HealthIndicatoras follows:

    @Component
class TPSHealth implements HealthIndicator {
TPSCounter counter;

@Override
public Health health() {
boolean health = counter.isWeak();
if (health) {
return Health.outOfService()
.withDetail("Too many requests", "OutofService")
.build();
}
return Health.up().build();
}

void updateTx(){
if(counter == null || counter.isExpired()){
counter = new TPSCounter();
}
counter.increment();
}
}

The health method checks whether the counter isWeak or not. If it is weak, it marks the instance as out of service.

Finally, we autowire TPSHealth into the GreetingController class, and then call health.updateTx() in the greet method, like this:

     Greet greet(){
logger.info("Serving Request....!!!");
health.updateTx();
return new Greet("Hello World!");
}

Go to the /application/health endpoint in the HAL browser, and see the status of the server.

Now open another browser, point to http://localhost:8080, and fire the service twice or thrice. Go back to the /application/health endpoint, and refresh to see the status. It would have been changed to out of service.

In this example, since there is no action taken other than collecting the health status, new service calls will still go through even though the status is out of service. But in the real world, a program should read the /application/health endpoint, and block further requests going to that instance.

主站蜘蛛池模板: 龙南县| 新平| 石楼县| 融水| 文昌市| 呼伦贝尔市| 东阳市| 鹰潭市| 渝北区| 沙田区| 栖霞市| 平江县| 武隆县| 邵东县| 东安县| 织金县| 丹江口市| 原阳县| 平南县| 阜阳市| 米脂县| 蓬莱市| 秦皇岛市| 乌鲁木齐市| 岳普湖县| 聂拉木县| 紫金县| 南开区| 白玉县| 湘西| 沧源| 吴桥县| 南郑县| 大埔区| 通渭县| 曲靖市| 仙桃市| 逊克县| 泰和县| 昌江| 苏尼特右旗|