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

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.

主站蜘蛛池模板: 民丰县| 绥滨县| 玉溪市| 藁城市| 孟州市| 永善县| 岗巴县| 襄汾县| 保山市| 东兴市| 六枝特区| 沙雅县| 马关县| 红河县| 南充市| 渝北区| 当阳市| 霸州市| 北川| 武宣县| 栖霞市| 东台市| 孟连| 甘孜县| 庆云县| 山阴县| 修文县| 巴林左旗| 阿拉尔市| 扶风县| 信阳市| 乡宁县| 敦化市| 环江| 沅陵县| 莱芜市| 中宁县| 凉城县| 夏津县| 江孜县| 灵武市|