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

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.

主站蜘蛛池模板: 林州市| 汾西县| 曲靖市| 哈尔滨市| 巴南区| 项城市| 汝阳县| 高淳县| 祁东县| 巨野县| 塔城市| 柘城县| 潞西市| 慈溪市| 沈丘县| 金昌市| 宁阳县| 内黄县| 兰坪| 毕节市| 繁昌县| 鞍山市| 泗洪县| 巴马| 浑源县| 黎川县| 阜城县| 伊宁市| 章丘市| 凤冈县| 和平县| 漠河县| 图木舒克市| 乌兰浩特市| 门头沟区| 涪陵区| 象州县| 泗洪县| 江西省| 电白县| 台南县|