Beginner's guide to Springboot - Actuator

techaiaiai 27 views 19 slides Sep 27, 2024
Slide 1
Slide 1 of 19
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19

About This Presentation

Spring boot actuator explained in detailed with coding example helpful for beginner for springboot


Slide Content

Springboot - Actuator

Introduction to Spring Boot Actuator Introduction: Spring Boot Actuator is a subproject that enhances the manageability and observability of Spring Boot applications. It offers built-in features for monitoring, management, and diagnostics. Key Objectives: Provide real-time insights into application health. Enable efficient metrics collection and analysis. Facilitate application management and configuration retrieval

Why Use Spring Boot Actuator? Real-time Insights: Actuator enables you to gain real-time insights into the health and behavior of your application. Metrics Collection: It allows for the collection of various application metrics, aiding in performance analysis. Application Management: Actuator provides endpoints for tasks like shutdown and configuration retrieval, simplifying application management.

Actuator Endpoints Endpoint Overview: Spring Boot Actuator exposes a set of predefined endpoints, each serving a specific purpose. Common Endpoints: Has essential endpoints such as ‘ / health’ ‘ / metrics’ ‘ / info’ and ‘ / env ’ Additional custom endpoints can also be created.

Health Endpoint /health Endpoint: The / health endpoint reports the application's overall health status. It performs checks on various components (e.g., database, external services) and returns a status (UP or DOWN ). Use Case : Actuator's /health endpoint is invaluable for monitoring the health of your application. How It Works : The /health endpoint performs a series of checks on various components, such as databases, messaging queues, and external services. It returns a simple status: "UP" if all checks pass, and "DOWN" if any check fails. Benefits : Monitoring health helps ensure the application is running smoothly. Load balancers and orchestrators use this endpoint to determine whether an instance is healthy and should receive traffic. Example : Operations teams can set up automated monitoring tools to periodically check the health status of all application instances and receive alerts if any instance becomes unhealthy.

Metrics Endpoint / metrics endpoint The / metrics endpoint collects and exposes a wide range of application metrics. Metrics can include JVM statistics, memory usage, request/response counts, and custom metrics. Use Case : Actuator's /metrics endpoint allows you to collect and expose various application metrics. How It Works : Spring Boot captures metrics related to memory usage, garbage collection, HTTP request/response statistics, and more. Custom metrics can also be added. Benefits : Tracking performance metrics helps you identify bottlenecks, memory leaks, and performance issues. It aids in optimizing your application for efficiency. Example : DevOps teams can use Actuator's metrics to visualize trends over time and proactively address performance degradation.

Info Endpoint / info endpoint: The / info endpoint provides custom metadata about the application. This is a great place to display version information, build details, or any other relevant data.

Environment Endpoint / env Endpoint: The / env e ndpoint displays information about application properties and environment variables. It aids in debugging and understanding the runtime environment. Use Case : Actuator's / configprops and / env endpoints provide insights into application properties and environment variables. How It Works : The / configprops endpoint lists all Spring @ ConfigurationProperties beans, which often correspond to application configuration. The / env endpoint shows environment-specific properties. Benefits : Retrieving configuration details simplifies debugging and troubleshooting. It allows you to verify that the application is using the correct settings in different environments. Example : Developers can use the / configprops endpoint to check if their custom configuration properties are correctly loaded and apply the expected values.

Shutdown Endpoint / shutdown endpoint: The / shutdown endpoint allows for a graceful shutdown of the application, but it requires proper security configurations to prevent misuse in production . Use Case : The /shutdown endpoint can be used for a graceful shutdown of the application. How It Works : You can configure Spring Security to secure the /shutdown endpoint, ensuring that only authorized users or scripts can initiate a shutdown. Benefits : In production environments, secure shutdowns are essential to prevent accidental or unauthorized termination of application instances. Example : Operations teams can use secure shutdown to gracefully stop an instance during maintenance or scaling down, ensuring no data loss or disruption.

Custom Endpoints Custom Endpoints : Spring Boot Actuator allows you to create custom endpoints tailored to your application's specific management needs. These endpoints can expose application-specific data or perform custom actions.

Configuration and Security Configuration : Configure Actuator endpoints in application.properties or application.yml Customize which endpoints are enabled, their properties, and security settings . In your application.properties or application.yml , you can enable or disable specific Actuator endpoints by using the management.endpoints.web.exposure.include property . This property controls which endpoints are accessible over HTTP . # Enable specific endpoints management.endpoints.web.exposure.include = health,info,metrics # Disable specific endpoints (by omitting them) # management.endpoints.web.exposure.include = health,info,metrics

Customize Endpoint Properties: Actuator endpoints often come with customizable properties that allow you to fine-tune their behavior. For example, you can set the response status of the / health endpoint to "UP" even if some checks fail . # Customize the health endpoint's status to "UP" even if checks fail management.endpoint.health.status.order =UP

Security Configuration Securing Actuator endpoints is crucial, especially in production environments where you want to restrict access to sensitive endpoints like /shutdown . You can use Spring Security or other authentication mechanisms to secure these endpoints.

import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest; import org.springframework.context.annotation.Bean ; import org.springframework.context.annotation.Configuration ; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @ EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure( HttpSecurity http) throws Exception { http . authorizeRequests () . requestMatchers (EndpointRequest.to("shutdown")). hasRole ("ADMIN") // Secure the /shutdown endpoint . antMatchers ("/**"). permitAll () // Allow public access to other endpoints .and() . httpBasic (); // Use HTTP Basic Authentication } }

Enabling Actuator Enabling Actuator : Add the Actuator dependency to your project . <dependency> < groupId > org.springframework.boot </ groupId > < artifactId >spring-boot-starter-actuator</ artifactId > </dependency> Configure Actuator endpoints based on your application's requirements.

Code Example 1: Configuration Server ( application.properties ) # Configuration Server port server.port =8888 # Git repository URL where configuration files are stored spring.cloud.config.server.git.uri =https://github.com/yourusername/config-repo.git # Git repository search paths spring.cloud.config.server.git.search -paths= configs

Code Example 2: Configuration Client ( application.properties ) # Application name (used to fetch configuration from the server) spring.application.name=product-service # URI of the Configuration Server spring.cloud.config.uri =http://config-server-host:8888 # Active profile spring.profiles.active =development

Code Example 3: Configuration File in Git Repository (product-service- development.properties ) # Database configuration spring.datasource.url= jdbc:mysql ://localhost:3306/ productsdb spring.datasource.username = dbuser spring.datasource.password = dbpassword # Service-specific configuration product- service.max -allowed-quantity=10 product- service.api -key=your- api -key

Code Example 4: Fetching Configuration in Configuration Client (Java Code) import org.springframework.beans.factory.annotation.Value ; import org.springframework.context.annotation.Configuration ; @Configuration public class ProductServiceConfiguration { @Value("${spring.datasource.url}") private String databaseUrl ; @Value("${product- service.max -allowed-quantity}") private int maxAllowedQuantity ; @Value("${product- service.api -key}") private String apiKey ; // Getter methods public String getDatabaseUrl () { return databaseUrl ; } public int getMaxAllowedQuantity () { return maxAllowedQuantity ; } public String getApiKey () { return apiKey ; } }