Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of developing scaffolding Integrated Spring Boot Actuator Monitoring

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge points about the method of developing scaffolding integrated Spring Boot Actuator monitoring. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Integration introduces dependency

Add the following dependencies to the pom.xml of the project

Org.springframework.boot spring-boot-starter-actuator profile

In application.yml

Management: # disable security check for actuator endpoints security: enabled: false access authentication

For example, by typing http://localhost:8080/actuator/health, we can view the current state of the application

{"status": "UP"}

This interface is often used for service probing or health check interfaces.

The integration is completed here.

Endpoint Endpoints

Actuator exposes all access points to JMX by default, but for security reasons, only health and info are exposed to Web.

All the access points provided by Actuator are listed in the official documentation. To expose more access points to Web, you need to add configuration to application.yml:

Management: endpoints: web: exposure: # contains all endpoints using "*". Note the quotation marks include: info, health, beans, env, metrics

Actuator provides the following interfaces, as shown in the following table.

HTTP method path description GET/auditevents shows audit events exposed by the application (such as authentication entry, order failure) GET/beans describes all Bean in the application context and their relationship GET/conditions is 1.0 / autoconfig, provides a condition for automatic configuration to take effect, and records which automatic configuration conditions have passed Which do not describe configuration properties through GET/configprops (including default values) how to inject BeanGET/env to get all environment properties GET/env/ {name} get specific environment property values by name GET/flyway provides a copy of Flyway database migration information GET/liquidbase displays fine information of Liquibase database migration GET/health reports the health indicators of the application These values are provided by the HealthIndicator implementation class to provide GET/heapdumpdump a copy of the application's JVM heap information GET/httptrace displays the HTTP footprint, and the last 100 HTTP request/repsponseGET/info get the application's customization information, which is provided by the properties headed by info to provide the content in the logfile returned by the GET/logfile (if logging.file or logging.path is set) GET/loggers displays and modifies the configured loggersGET/metrics reports various application metrics information For example, memory usage and HTTP request count GET/metrics/ {name} report application metrics with specified names GET/scheduledtasks display scheduled task information in the application GET/sessions if we use the HTTP sessions information in the Spring Session presentation application POST/shutdown closes the application and requires endpoints.shutdown.enabled to be set to trueGET/mappings to describe all URI paths And their mapping relationship with the controller (including Actuator endpoints) GET/threaddump takes a snapshot of thread activity GET/prometheus exposes metrics in a format that the Prometheus server can grab. Need to rely on micrometer-registry-prometheus.

Let's focus on what the actual project uses.

Health

Health is mainly used to check the running status of applications, which is one of the most high-frequency monitoring points we use. Monitor the running status of the instance, and the reasons why the application is not "healthy", such as database connection, insufficient disk space, etc.

Whether the details of health information are made public can be configured, for example:

Management.endpoint.health.show-details=always

Never never shows details, default

When-authorized details are displayed only to authorized users. You can use to configure the authorization role management.endpoint.health.roles.

Always displays details to all users.

Spring Boot automatically configures what is listed in the following table of HealthIndicators. You can also configure to enable or disable the selected metric management.health.key.enabled,key, as shown in the following table:

Key name description cassandraCassandraDriverHealthIndicator checks to see if the Cassandra database is started. CouchbaseCouchbaseHealthIndicator checks to see if the Couchbase cluster is started. DbDataSourceHealthIndicator checks to see if a connection DataSource can be obtained. DiskspaceDiskSpaceHealthIndicator checks for insufficient disk space. ElasticsearchElasticsearchRestHealthIndicator checks to see if the Elasticsearch cluster is started. HazelcastHazelcastHealthIndicator checks to see if the Hazelcast server is started. InfluxdbInfluxDbHealthIndicator checks to see if the InfluxDB server is started. JmsJmsHealthIndicator checks to see if the JMS agent is started. LdapLdapHealthIndicator checks to see if the LDAP server is started. MailMailHealthIndicator checks to see if the mail server is started. MongoMongoHealthIndicator checks to see if the Mongo database is started. Neo4jNeo4jHealthIndicator checks to see if the Neo4j database is started. PingPingHealthIndicator always responds to UP. RabbitRabbitHealthIndicator checks to see if the Rabbit server is started. RedisRedisHealthIndicator checks to see if the Redis server is started. SolrSolrHealthIndicator checks to see if the Solr server is started.

You can turn off specific health check indicators in the configuration file, such as turning off the health check for redis:

Management.health.redis.enabled=falseInfo

Info is the configuration information that we configure in the configuration file that starts with info. You can customize the data exposed by the info endpoint by setting the Spring property. All Environment properties under the info.* key are automatically exposed. For example, you can add the following settings to the application.yaml file:

Info: app: name: spring-boot-actuator version: 1.0.0 test: test encoding: @ project.build.sourceEncoding@ source: @ java.version@ target: @ java.version@

To start the project, visit: http://localhost:8080/actuator/info returns some information as follows:

{"app": {"name": "spring-boot-actuator", "version": "1.0.0", "test": "test", "encoding": "UTF-8", "source": "1.8.0,102" "target": "1.8.0,102"}} Security

Pay special attention to the security of the exposed URL. For example, / actuator/env can obtain all the environment variables of the current machine and cannot be exposed to the public network.

In order to ensure the security of the monitoring interface exposed by actuator, the dependent spring-boot-start-security dependency for security control needs to be added, and verification information is required when accessing the application monitoring endpoint.

Forms-based HTTP authentication is used by default to protect endpoints.

Security dependency, you can choose not to add, not for security management, but this is not recommended.

Org.springframework.boot spring-boot-starter-security

The code is as follows:

@ Configurationpublic class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {/ * * version1: * 1. Restrict access to'/ shutdown' endpoints, allowing only ACTUATOR_ADMIN access to * 2. Allow external access to other endpoints * 3. Allow external access to static resources * 4. Allow external access to'/'* 5. Other visits need to be verified * version2: * 1. Restrict access to all endpoints, allowing only ACTUATOR_ADMIN access to * 2. Allow external access to static resources * 3. Allow external access to'/'* 4. Other visits need to be verified * / @ Override protected void configure (HttpSecurity http) throws Exception {/ / version1// http//. AuthorizeRequests () /. RequestMatches (EndpointRequest.to (ShutdownEndpoint.class)) / / .hasRole ("ACTUATOR_ADMIN") / / .requestMatrices (EndpointRequest. ToAnyEndpoint () / / .permitAll () / / .requestMatrices (PathRequest.toStaticResources (). AtCommonLocations ()) / / .permitAll () / / .permitAll ("/") / / .permitAll () / / .antMatrices ("/ * *") / / .authenticated () / / .and () / / .httpBasic () / / version2 http .authorizeRequests () .requestMatrices (EndpointRequest.toAnyEndpoint ()) .hasRole ("ACTUATOR_ADMIN") .requestMatrices (PathRequest.toStaticResources (). AtCommonLocations ()) .permitAll (). AntMatchers ("/"). PermitAll () .antMatrices ("/ * *") .authenticated () .and () .httpBasic () }}

The relevant configurations of application.properties are as follows:

# Spring Security Default user name and passwordspring.security.user.name=actuatorspring.security.user.password=actuatorspring.security.user.roles=ACTUATOR_ADMIN Advanced Custom Health check

To provide custom health information, you can register the Spring bean that implements the HealthIndicator interface. You need to provide the implementation of the health () method and return the Health response. The Health response should contain the status and, optionally, additional details to display. The following code shows a sample HealthIndicator implementation:

@ Componentpublic class EasyAdminHealthIndicator extends AbstractHealthIndicator {@ Override public void doHealthCheck (Health.Builder builder) throws Exception {boolean checkHealth = check (); if (checkHealth) {builder.up ();} else {builder.down ();} builder.withDetail ("code", "200") .withdetail (" msg "," i am ok ") } private boolean check () {return true;}}

To start the project, visit: http://localhost:8080/actuator/health returns the following information:

{"status": "UP", "components": {"db": {"status": "UP", "details": {"database": "MySQL" "validationQuery": "isValid ()"}}, "diskSpace": {"status": "UP", "details": {"total": 332861009920 "free": 312464228352, "threshold": 10485760, "exists": true}} "easyAdmin": {/ / do do do "status": "UP", "details": {"code": "200" "msg": "i am ok"}, "mail": {"status": "UP" "details": {"location": "smtp.qq.com:-1"}}, "ping": {"status": "UP"}} custom metrics metrics

Two types of commonly used indicators (Metric Type)

Gauge, counter, summary, timer

Gauge: can increase and subtract counters to reflect the current moment state of a value. For example, the current weight of the weighing sensor and the current temperature of the temperature sensor.

Method 1:

Gauge.builder (gn.temperature.gauge, new AtomicInteger (37), AtomicInteger::get)

Method 2:

Registry.gauge ("gn.temperature.gauge", Tags.of ("site", "SiteA", "cab", "cab01"), new AtomicInteger (37))

Counter: only increase but not decrease the counter, is a special case of Gauge. It is suitable for counting scenarios that are reset only when the server is restarted. For example, "number of user visits", "number of failures of an interface" and so on. API is used in a similar way.

Counter counter = Counter.builder ("gn.beat.counter") .tags ("site", "SiteA", "function", "foo") .description ("for request errors") .register (registry); counter.increment ()

The way it fits into the system

Method 1: business system burying point

@ Componentpublic class SampleBean {private final Counter counter; private final List list = new CopyOnWriteArrayList ();; public SampleBean (MeterRegistry registry) {this.counter = registry.counter ("laker.counter"); registry.gauge ("laker.size", Tags.empty (), this.list.size ());} public void handleMessage (String message) {this.counter.increment (); list.add (message) } public void handleRemoveMessage (String message) {list.remove (message);}}

Method 2: MeterBinder

The MeterBinder interface is provided in SpringBoot for declaring and registering meterRegistry. Custom Metrics only needs to implement the MeterBinder interface, and Spring will automatically discover and complete the subsequent chores.

@ Beanpublic class MyMetrics implements MeterBinder {@ Override public void bindTo (MeterRegistry meterRegistry) {/ / add related metrics meterRegistry.gauge ("laker.gauge", Tags.of ("site", "SiteA"), new AtomicInteger (37));}}

Access http://localhost:8080/actuator/metrics/laker.counter in a browser

The results are as follows:

{

"name": "laker.counter"

"description": null

"baseUnit": null

"measurements": [

{

"statistic": "COUNT"

Value: 9.0

}

]

"availableTags": []

}

For other uses, please refer to: MetricsAutoConfiguration.java

PID PORT process monitoring

ApplicationPidFileWriter creates a file that contains the application PID (by default, in the application directory, the file name is application.pid).

WebServerPortFileWriter creates a file (or files) that contains the port of the running Web server (by default, in the application directory, the file name is application.port).

By default, these writers are not activated:

@ SpringBootApplicationpublic class LakerMapApplication {public static void main (String [] args) {SpringApplication springApplication = new SpringApplication (LakerMapApplication.class); springApplication.addListeners (new ApplicationPidFileWriter (), new WebServerPortFileWriter (". / laker.port")); springApplication.run (args);}}

Configuration file:

Spring: pid: # File written to pid file:. / laker.pid # whether to throw an exception fail-on-write-error: false Custom Management Endpoint path management.endpoints.web.base-path=/manage when the pid file cannot be written

Change the endpoint from / actuator/ {id} to / manage/ {id} (for example, / manage/info).

You can use this management.endpoints.web.path-mapping attribute if you want to map endpoints to different paths.

The following example remaps / actuator/health to / healthcheck:

Management.endpoints.web.base-path=/management.endpoints.web.path-mapping.health=healthcheck Custom Management Server Port management.server.port=8081management.server.address=127.0.0.1 exposes data to Prometheus

Because of the nature of exposing internal information, Actuator can also be integrated with some external application monitoring systems (Prometheus, Graphite, DataDog, Influx, Wavefront, New Relic, etc.). These monitoring systems provide excellent dashboards, graphics, analysis and alerts to help you monitor and manage your applications through a unified and friendly interface.

Add dependency

In order for Spring Boot applications to integrate with Prometheus, you need to increase micrometer-registry-prometheus dependencies.

Io.micrometer micrometer-registry-prometheus

After adding the above dependencies, Spring Boot will automatically configure PrometheusMeterRegistry and CollectorRegistry to collect and export metrics data in a format that Prometheus can grab.

All relevant data is exposed at the / prometheus endpoint of Actuator. Prometheus can crawl the endpoint to get metric data on a regular basis.

After adding the micrometer-registry-prometheus dependency, we access the http://localhost:8080/actuator/prometheus address.

These are all the contents of this article entitled "developing scaffolding Integrated Spring Boot Actuator Monitoring". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report