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

How to use SpringBoot Admin

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

Share

Shulou(Shulou.com)06/02 Report--

This article is to share with you about how to use SpringBoot Admin. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Introduction

Spring Boot Admin is an open source project on Github that provides a concise visual WEB UI based on Spring Boot Actuator. It is a simple interface for managing Spring Boot applications and provides the following functions:

Display name/id and version number

Show online statu

Logging log level management

JMX beans management

Threads session and thread management

Trace application request tracking

Application operation parameter information, such as:

Java system Properties

Java environment variable properties

Memory information

Spring environment properties

Spring Boot Admin consists of a server and a client, and the following configuration allows Spring Boot Admin to run.

Use the server side

1. Introduce the relevant jar package into the pom file

Create a new Spring Boot project for admin-server and introduce the server-related jar package into the pom file

De.codecentric spring-boot-admin-server 1.5.3 de.codecentric spring-boot-admin-server-ui 1.5.3 de.codecentric spring-boot-admin-starter-client 1.5.3

The introduction of spring-boot-admin-starter-client is to enable server itself to find itself (which is also a client).

2. Application.yml configuration

The configuration of application.yml is as follows: except that the configuration of server.port=8083 is the service port published by server, the other configuration is that of server itself as a client, including indicating the address pointing to the server and the basic information of the current application. You can read the relevant configuration of pom.xml using @ @.

In the following explanation of Client configuration, you can see a similar configuration below.

Server: port: 8083spring: boot: admin: url: http://localhost:8083info: name: server description: @ project.description@ version: @ project.version@

3. Configure the log level

In the sibling directory of application.yml, add the file logback.xml to configure the level of the log, which contains the following:

DEBUG is configured here so that you can view the interaction between the server side and the client side through the console log.

4. Add entry method notes

Add the @ EnableAdminServer annotation to the entry method.

@ Configuration@EnableAutoConfiguration@EnableAdminServerpublic class ServerApplication {public static void main (String [] args) {SpringApplication.run (ServerApplication.class, args);}}

5. Start the project

After launching the admin-server project, you can see the currently registered client, click on the details, and view other details.

Client end

In the above server-side configuration, server itself is registered to itself as a client, so the client configuration is compared with the server-side configuration, as shown below.

Create an admin-client project and add related client dependency packages to pom.xml.

1. Pom.xml adds client dependencies

De.codecentric spring-boot-admin-starter-client 1.5.3

2. Application.yml configuration

Configure registry address and other information in application.yml:

Spring: boot: admin: url: http://localhost:8083info: name: client description: @ project.description@ version: @ project.version@endpoints: trace: enabled: true sensitive: false

3. Configure log files

In the sibling directory of application.yml, add the file logback.xml to configure the level of the log, which contains the following:

Configured to the level of DEBUG, you can output communication information with the server, so that we can detect the heartbeat later and understand how to implement Spring Boot Admin.

4. Start the Admin-Client application

Start the client project, listen to the startup of the client on the server, and give a message on the page. After startup, the interface of the server is displayed as follows: (both clients are in UP status)

Above, you can use various monitoring services of Spring Boot Admin. Let's talk about how the client and server do heartbeat detection.

Heartbeat detection / health detection principle

In Spring Boot Admin, the server acts as a registry, and it monitors the current status of all clients. To know whether the current client is down, the newly released client can also actively register with the server.

The server and the client communicate through a specific interface (/ health interface) to monitor the status of the client. Because the client and server cannot guarantee the release order.

There are the following scenarios to consider:

The client starts first, and then the server starts

The server starts first, and the client starts later

The server is running and the client is offline

The client is running and the server is offline

Therefore, in order to solve the above problems, both the client and the server need to set up a task listener to monitor each other's heartbeat regularly and update the client status in time on the server.

The above configuration uses the method of client active registration.

Debugging preparation

In order to understand how Spring Boot Admin is implemented, you can understand the communication between the server and the client through DEBUG and viewing logs (heartbeat detection)

Right-click spring-boot-admin-server and spring-boot-admin-starter-client,Maven- > DownLoad Sources and Documentation in pom.xml

Set the log level to DEBUG in logback.xml

The client initiates a POST request

Client related classes

RegistrationApplicationListener

ApplicationRegistrator

The startRegisterTask of RegistrationApplicationListener is called when the client starts. This method requests the server POST every registerPeriod = 10000L (10 seconds: default), telling the server that it currently has a heartbeat.

RegistrationApplicationListener

@ EventListener @ Order (Ordered.LOWEST_PRECEDENCE) public void onApplicationReady (ApplicationReadyEvent event) {if (event.getApplicationContext () instanceof WebApplicationContext & & autoRegister) {startRegisterTask ();}} public void startRegisterTask () {if (scheduledTask! = null & &! scheduledTask.isDone ()) {return } scheduledTask = taskScheduler.scheduleAtFixedRate (new Runnable () {@ Override public void run () {registrator.register ();}, registerPeriod); LOGGER.debug ("Scheduled registration task for every {} ms", registerPeriod);}

ApplicationRegistrator

Public boolean register () {boolean isRegistrationSuccessful = false; Application self = createApplication (); for (String adminUrl: admin.getAdminUrl ()) {try {@ SuppressWarnings ("rawtypes") ResponseEntity response = template.postForEntity (adminUrl, new HttpEntity (self, HTTP_HEADERS), Map.class) If (response.getStatusCode (). Equals (HttpStatus.CREATED)) {if (registeredId.compareAndSet (null, response.getBody (). Get ("id"). ToString ()) {LOGGER.info ("Application registered itself as {}", response.getBody ()) } else {LOGGER.debug ("Application refreshed itself as {}", response.getBody ());} isRegistrationSuccessful = true; if (admin.isRegisterOnce ()) {break }} else {if (unsuccessfulAttempts.get () = = 0) {LOGGER.warn ("Application failed to registered itself as {}. Response: {}. Further attempts are logged on DEBUG level ", self, response.toString ();} else {LOGGER.debug (" Application failed to registered itself as {}. Response: {} ", self, response.toString () } catch (Exception ex) {if (unsuccessfulAttempts.get () = = 0) {LOGGER.warn ("Failed to register application as {} at spring-boot-admin ({}): {}. Further attempts are logged on DEBUG level ", self, admin.getAdminUrl (), ex.getMessage ();} else {LOGGER.debug (" Failed to register application as {} at spring-boot-admin ({}): {} ", self, admin.getAdminUrl (), ex.getMessage ()) } if (! isRegistrationSuccessful) {unsuccessfulAttempts.incrementAndGet ();} else {unsuccessfulAttempts.set (0);} return isRegistrationSuccessful;}

In the main register () method, a Restful request is POST to the server with the address of / api/applications

And bring their own information in the past, the server accepts the request, through the sha-1 algorithm to calculate the unique ID of the customer order, query the hazelcast cache database, such as the first time, write, otherwise update.

The server receives and processes the request related classes

RegistryController

@ RequestMapping (method = RequestMethod.POST) public ResponseEntity register (@ RequestBody Application application) {Application applicationWithSource = Application.copyOf (application) .withSource ("http-api") .build (); LOGGER.debug ("Register application {}", applicationWithSource.toString ()); Application registeredApp = registry.register (applicationWithSource); return ResponseEntity.status (HttpStatus.CREATED) .body (registeredApp);}

ApplicationRegistry

Public Application register (Application application) {Assert.notNull (application, "Application must not be null"); Assert.hasText (application.getName (), "Name must not be null"); Assert.hasText (application.getHealthUrl (), "Health-URL must not be null"); Assert.isTrue (checkUrl (application.getHealthUrl ()), "Health-URL is not valid") Assert.isTrue (StringUtils.isEmpty (application.getManagementUrl ()) | | checkUrl (application.getManagementUrl ()), "URL is not valid"); Assert.isTrue (StringUtils.isEmpty (application.getServiceUrl ()) | | checkUrl (application.getServiceUrl ()), "URL is not valid"); String applicationId = generator.generateId (application) Assert.notNull (applicationId, "ID must not be null"); Application.Builder builder = Application.copyOf (application) .withID (applicationId); Application existing = getApplication (applicationId); if (existing! = null) {/ / Copy Status and Info from existing registration. Builder.withStatusInfo (existing.getStatusInfo ()) .withInfo (existing.getInfo ());} Application registering = builder.build (); Application replaced = store.save (registering); if (replaced = = null) {LOGGER.info ("New Application {} registered", registering); publisher.publishEvent (new ClientApplicationRegisteredEvent (registering)) } else {if (registering.getId (). Equals (replaced.getId () {LOGGER.debug ("Application {} refreshed", registering);} else {LOGGER.warn ("Application {} replaced by Application {}", registering, replaced);}} return registering;}

HazelcastApplicationStore (cache database)

The publisher.publishEvent event subscription method is used in the above update status, and the recipient receives the event and does the business processing of the application. This method is used for code reusability, because the server regularly polls the client to update the client's status on the server.

The classes designed by pulishEvent are:

StatusUpdateApplicationListener- > onClientApplicationRegistered

StatusUpdater- > updateStatus

We will not expand it in detail here. As mentioned below, through the log, you can see the POST requests regularly sent by the client:

Server timing polling

When the server is down, the server cannot receive the request, and the server does not know what the status of the client is. (of course, it can be said that the server does not receive the information from the client within a certain period of time, so it thinks that the client is dead, which is also a way to deal with it. In Spring Boot Admin, the server conducts mentality detection on the client by regularly polling the client's / health interface.

The main classes designed here are:

StatusUpdateApplicationListene

@ EventListener public void onApplicationReady (ApplicationReadyEvent event) {if (event.getApplicationContext () instanceof WebApplicationContext) {startStatusUpdate ()}} public void startStatusUpdate () {if (scheduledTask! = null & &! scheduledTask.isDone ()) {return } scheduledTask = taskScheduler.scheduleAtFixedRate (new Runnable () {@ Override public void run () {statusUpdater.updateStatusForAllApplications ();}, updatePeriod); LOGGER.debug ("Scheduled status-updater task for every {} ms", updatePeriod);}

StatusUpdater

Public void updateStatusForAllApplications () {long now = System.currentTimeMillis (); for (Application application: store.findAll ()) {if (now-statusLifetime > application.getStatusInfo (). GetTimestamp ()) {updateStatus (application);} public void updateStatus (Application application) {StatusInfo oldStatus = application.getStatusInfo (); StatusInfo newStatus = queryStatus (application) Boolean statusChanged =! newStatus.equals (oldStatus); Application.Builder builder = Application.copyOf (application) .withStatusInfo (newStatus); if (statusChanged & &! newStatus.isOffline () & &! newStatus.isUnknown ()) {builder.withInfo (queryInfo (application));} Application newState = builder.build (); store.save (newState) If (statusChanged) {publisher.publishEvent (new ClientApplicationStatusChangedEvent (newState, oldStatus, newStatus));}} Thank you for reading! This is the end of the article on "how to use SpringBoot Admin". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

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