Building My First Microservice - Part 2 (Actuator)

 Imagine having a control panel to monitor and manage your Spring Boot applications. The ability to peek under the hood and take action. That's the superpower Actuator brings to the table, exposing insightful endpoints and allowing endless extension through custom endpoints.

In this hands-on post, we'll explore Actuator, see it in action, and learn how to create custom endpoints tailored to your app's needs.


What is Actuator?

Actuator enables production-ready features like:

  • Health checks - Check the health status of your app and dependencies. Got a heartbeat?
  • Metrics - How's the CPU? Memory? HTTP Traffic? Get valuable usage metrics.
  • API Info - View details about your API endpoints, routes, dependencies.
  • Environment - List and update configurations on the fly.

Actuator exposes these features through a set of web endpoints like '/actuator/health' or '/actuator/metrics'. Think of it as a dashboard for controlling your apps.

In this post, we'll explore how Actuator makes it a cinch to add things like health checks, metrics, and dynamic management capabilities to your Spring Boot apps.

Getting Started with Actuator

Enabling Actuator is as simple as adding the 'spring-boot-starter-actuator' dependency to your Spring Boot app:


<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

This enables all the auto-configuration needed to use Actuator.

By default, all endpoints are disabled for security reasons. You need to explicitly expose the endpoints you want to use like this:


Now let's look at some of the capabilities Actuator unlocks!

Monitoring System Health

One of the most useful endpoints is the health check at '/actuator/health'. This returns valuable information about the health of your app and dependent systems:

If all checks are healthy, you get a simple UP status. If any health checks fail, the status changes to DOWN.

This allows rapidly detecting issues with your services. Plus you can add custom health indicators to monitor specific business functionality.

Tracking Performance Metrics

The metrics endpoint at '/actuator/metrics' is a goldmine of insightful metrics about your app, JVM, system etc. 

You get builtin metrics for things like:

- HTTP requests

- CPU/Memory usage

- Cache utilization 

- Data source connections

- RestTemplate calls

- Many more

This makes it easy to pinpoint performance problems without any additional configuration needed.

Building Custom Management Endpoints

Here's where Actuator really shines - you can create fully customized endpoints to manage your app dynamically at runtime!

For example:

- Change log levels on the fly

- Reload configurations 

- Gather aggregated business metrics

- Execute cleanup/maintenance tasks

You just need to create an '@Endpoint' class and expose operations like read, write, delete. Map these to HTTP GET, POST, DELETE and you've got a production-ready management interface!



package com.aggrandizer.firstApp;

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
@Endpoint(id = "stage")
public class StageEndpoint {

Map<String,Stage> stages = new ConcurrentHashMap<>();
@ReadOperation
public Map<String,Stage> getAllStages(){
return stages;
}

@ReadOperation
public Stage getStage(@Selector String name){
return stages.get(name);
}

@WriteOperation
public void setValue(@Selector String name,int stage){
stages.put(name,new Stage(stage));
}


static class Stage{
int value;

public Stage(int value) {
this.value = value;
}

public int getValue() {
return value;
}

public void setValue(int value) {
this.value = value;
}
}
}


In this example, I'm not using the Lombok dependency to reduce boilerplate code. However, in future posts I plan to cover how Lombok can help clean up your code by automatically generating getters, setters, builders, and more.

Testing the endpoints with postman:

POST  -  http://localhost:8080/actuator/stage/st001


GET  -  http://localhost:8080/actuator/stage

Securing Your Endpoints

With the power of endpoints, we also need to consider security. Here are some ways Actuator helps:


  • Authentication - Secure endpoints with basic auth or OAuth.
  • Access controls - Limit access to endpoints through role-based authorization.
  • Transport encryption - Enforce HTTPS for all endpoints.

Apply protections fitting your use case - unauthorized access is dangerous!

Conclusion

Actuator provides incredible insights into our apps through its metrics, health, info endpoints and more. With custom endpoints, the possibilities are endless for monitoring, controlling, and extending your apps!

I hope this post provided an actionable overview of Actuator's capabilities. Let me know if you have any other topics you'd like me to cover or have feedback!

Post a Comment

Previous Post Next Post