Spring Boot 2.0 Cookbook - Second Edition
eBook - ePub

Spring Boot 2.0 Cookbook - Second Edition

Alex Antonov

Buch teilen
  1. English
  2. ePUB (handyfreundlich)
  3. Über iOS und Android verfügbar
eBook - ePub

Spring Boot 2.0 Cookbook - Second Edition

Alex Antonov

Angaben zum Buch
Buchvorschau
Inhaltsverzeichnis
Quellenangaben

Über dieses Buch

Take your application development skills to the next level by implementing Spring Boot features effectivelyAbout This Book• This collection of effective recipes serves as guidelines for Spring Boot application development• Get up to date with features of the latest version of Spring Boot 2.0• Tips and tricks to improve your efficiency through the stages of software developmentWho This Book Is ForThis book is for Java Developers who have good knowledge and understanding of Spring and Java application development.What You Will Learn• Get to know Spring Boot Starters and create custom auto-configurations• Work with custom annotations that enable bean activation• Use DevTools to easily develop and debug applications• Learn the effective testing techniques by integrating Cucumber and Spock• Observe an eternal application configuration using Consul• Move your existing Spring Boot applications to the cloud• Use Hashicorp Consul and Netflix Eureka for dynamic Service Discovery• Understand the various mechanisms that Spring Boot provides to examine an application's healthIn DetailThe Spring framework provides great flexibility for Java development, which also results in tedious configuration work. Spring Boot addresses the configuration difficulties of Spring and makes it easy to create standalone, production-grade Spring-based applications.This practical guide makes the existing development process more efficient. Spring Boot Cookbook 2.0 Second Edition smartly combines all the skills and expertise to efficiently develop, test, deploy, and monitor applications using Spring Boot on premise and in the cloud. We start with an overview of the important Spring Boot features you will learn to create a web application for a RESTful service. Learn to fine-tune the behavior of a web application by learning about custom routes and asset paths and how to modify routing patterns. Address the requirements of a complex enterprise application and cover the creation of custom Spring Boot starters.This book also includes examples of the new and improved facilities available to create various kinds of tests introduced in Spring Boot 1.4 and 2.0, and gain insights into Spring Boot DevTools. Explore the basics of Spring Boot Cloud modules and various Cloud starters to make applications in "Cloud Native" and take advantage of Service Discovery and Circuit Breakers.Style and approachThis practical guide follows a recipe-based approach and provides extremely helpful guidelines to build, configure, and customize your Spring Boot applications.

Häufig gestellte Fragen

Wie kann ich mein Abo kündigen?
Gehe einfach zum Kontobereich in den Einstellungen und klicke auf „Abo kündigen“ – ganz einfach. Nachdem du gekündigt hast, bleibt deine Mitgliedschaft für den verbleibenden Abozeitraum, den du bereits bezahlt hast, aktiv. Mehr Informationen hier.
(Wie) Kann ich Bücher herunterladen?
Derzeit stehen all unsere auf Mobilgeräte reagierenden ePub-Bücher zum Download über die App zur Verfügung. Die meisten unserer PDFs stehen ebenfalls zum Download bereit; wir arbeiten daran, auch die übrigen PDFs zum Download anzubieten, bei denen dies aktuell noch nicht möglich ist. Weitere Informationen hier.
Welcher Unterschied besteht bei den Preisen zwischen den Aboplänen?
Mit beiden Aboplänen erhältst du vollen Zugang zur Bibliothek und allen Funktionen von Perlego. Die einzigen Unterschiede bestehen im Preis und dem Abozeitraum: Mit dem Jahresabo sparst du auf 12 Monate gerechnet im Vergleich zum Monatsabo rund 30 %.
Was ist Perlego?
Wir sind ein Online-Abodienst für Lehrbücher, bei dem du für weniger als den Preis eines einzelnen Buches pro Monat Zugang zu einer ganzen Online-Bibliothek erhältst. Mit über 1 Million Büchern zu über 1.000 verschiedenen Themen haben wir bestimmt alles, was du brauchst! Weitere Informationen hier.
Unterstützt Perlego Text-zu-Sprache?
Achte auf das Symbol zum Vorlesen in deinem nächsten Buch, um zu sehen, ob du es dir auch anhören kannst. Bei diesem Tool wird dir Text laut vorgelesen, wobei der Text beim Vorlesen auch grafisch hervorgehoben wird. Du kannst das Vorlesen jederzeit anhalten, beschleunigen und verlangsamen. Weitere Informationen hier.
Ist Spring Boot 2.0 Cookbook - Second Edition als Online-PDF/ePub verfügbar?
Ja, du hast Zugang zu Spring Boot 2.0 Cookbook - Second Edition von Alex Antonov im PDF- und/oder ePub-Format sowie zu anderen beliebten Büchern aus Ciencia de la computación & Programación en Java. Aus unserem Katalog stehen dir über 1 Million Bücher zur Verfügung.

Information

Health Monitoring and Data Visualization

In this chapter, we will cover the following recipes:
  • Writing custom health indicators
  • Configuring management context
  • Emitting metrics
  • Monitoring Spring Boot via JMX
  • Managing Spring Boot via SSHd Shell and writing custom remote Shell commands
  • Integrating Micrometer metrics with Graphite
  • Integrating Micrometer metrics with Dashing

Introduction

In the previous chapter, you learned a few techniques to efficiently package and get the application ready for deployment and we looked at a number of techniques to provide an environmental configuration without changing the code. With the deployment and configuration woes behind us, the last (but not least) important step remains—ensuring that we have complete visibility, monitoring, and management control of our application, as it is running in the production environment and is exposed to the harsh environment of customers' (ab)use.
Just as airline pilots don't like to fly blind, developers don't get excited if they can't see how their beloved application, that they worked hard on, performs in production. We want to know, at any given time, what the CPU utilization is like, how much memory we are consuming, whether our connection to the database is up and available, the number of customers who use the system in any given time interval, and so on. Not only do we want to know all these things, but we also want to be able to see it in pretty charts, graphs, and visual dashboards. These come in very handy to put on the big Plasma displays for monitoring as well as impressing your boss, so as to show that you are on the top of things and have it all under control.
This chapter will help you learn the necessary techniques to enhance our application in order to expose custom metrics, health statuses, and so on, as well as how to get the monitoring data out of our application and either store it in Graphite for historical reference or use this data to create real-time monitoring dashboards using the Dashing and Grafana frameworks. We will also take a look at the capability to connect to running instances and perform various management tasks using the powerful CRaSH framework integration.

Writing custom health indicators

Knowing the state of the application that is running in production, especially in a large-scale distributed system, is just as (if not more) important as having things such as automated testing and deployment. In today's fast-paced IT world, we can't really afford much downtime, so we need to have the information about the health of the application at our fingertips, ready to go at a minute's notice. If the all-so-important database connections go down, we want to see it right away and be able to quickly remedy the situation; the customers are not going to be waiting around for long before they go to another site.
We will resume working on our BookPub application in the state in which we left it in the previous chapter. In this recipe, we will add the necessary Spring Boot starters to enable the monitoring and instrumentation of our application and will even write our own health indicator.

How to do it...

  1. The first thing that we need to do is add a dependency to the Spring Boot Actuator starter in our build.gradle file with the following content:
dependencies { ... compile("org.springframework.boot:spring-boot-starter-
data-rest") // compile("org.springframework.boot:spring-boot-starter-
jetty") //
Need to use Jetty instead of Tomcat compile("org.springframework.boot:spring-boot-starter-
actuator") compile project(':db-count-starter') ... }
  1. Adding this dependency alone already gives us the ability to access the Spring management /actuator/* endpoints, such as /env, /info, /metrics, and /health, (though they are disabled by default, unless a management.endpoints.web.exposure.include=* property is configured in the application.properties file). So, let's start our application by executing the ./gradlew clean bootRun command line and then we can access the newly available /health endpoint by opening our browser and going to http://localhost:8080/actuator/health so as to see the new endpoint in action, as shown in the following screenshot:
  1. To get more details about the health state of our application, let's configure it to show the detailed health output by adding the management.endpoint.health.show-details=always property to the application.properties file and then restarting our application. Now, when we go to http://localhost:8080/actuator/health in the browser, we should see something similar to the following screenshot:
  1. With the actuator dependency added, and detailed /health endpoint configured, we can now add and perform all kinds of monitoring functions on our application. Let's go ahead and populate the /info endpoint with some data by adding a directive to the build.gradle file located at the root of our project with the following content:
springBoot { buildInfo { properties { additional = [ 'description' : project.description ] } } } 
  1. Next, we will create a new properties file named gradle.properties in the root directory of our project with the following content:
version=0.0.1-SNAPSHOT description=BookPub Catalog Application
  1. We will also add rootProject.name='BookPub-ch7' to the settings.gradle file located in the root directory of our project.
  2. Now, let's start our application by executing ./gradlew clean bootRun and then we can access the newly available /info endpoint by opening our browser and going to http://localhost:8080/actuator/info to see the new endpoint in action, as follows:
  1. As we have got the hang of how things work, let's go ahead and make our custom health indicator, which will be accessible via the /health endpoint in order to report the count status of the entries for each of our repositories. If they are greater than or equal to zero, we are UP, otherwise we are not really sure what's going on. Obviously, if an exception has occurred, we would be reporting DOWN. Let's start by relaxing the getRepositoryName(...) method visibility from private to protected in the DbCountRunner.java file located in the db-count-starter/src/main/java/com/example/bookpubstarter/dbcount directory at the root of our project.
  2. Next, we will add the same dependency to the compile("org.springframework.boot:spring-boot-starter-actuator") library in the build.gradle file in the db-count-starter directory at the root of our project.
  1. Now, we will create a new file named DbCountHealthIndicator.java in the db-count-starter/src/main/java/com/example/bookpubstarter/dbcount directory at the root of our project with the following content:
public class DbCountHealthIndicator implements HealthIndicator { private CrudRepository repository; public DbCountHealthIndicator(CrudRepository repository) { this.repository = repository; } @Override public Health health() { try { long count = repository.count(); if (count >= 0) { return Health.up().withDetail("count", 
count).build(); } else { return Health.unknown().withDetail("count",
count).build(); } } catch (Exception e) { return Health.down(e).build(); } } }
  1. Next, we will modify the @Import annotation in the EnableDbCounting.java file located in the db-count starter/src/main/java/com/example/bookpubstarter/dbcount directory at the root of our project with the following content:
@Import({DbCountAutoConfiguration.class, HealthIndicatorAutoConfiguration.class})
  1. Finally, for the automatic registration of our HealthIndicator class, we will enhance the DbCountAutoConfiguration.java file located in the db-count-starter/src/main/java/com/example/bookpubstarter/dbcount directory at the root of our project with the following content:
@Autowired private HealthAggregator healthAggregator; @Bean public HealthIndicator dbCountHealthIndicator(Collection<CrudRepository> repositories) { CompositeHealthIndicator compositeHealthIndicator = new 
CompositeHealthIndicator(healthAggregator); for (CrudRepository repository : repositories) { String name = DbCountRunner.getRepositoryName
(repository.getClass()); compositeHealthIndicator.addHealthIndicator(name, new
DbCountHealthIndicator(repository)); } return compositeHealthIndicator; }
  1. So, let's start our application by executing the ./gradlew clean bootRun command line, and then we can access the /health endpoint by opening our browser and going to http://localhost:8080/actuator/health to see our new HealthIndicator class in action, as follows:

How it works...

The Spring Boot Actuator starter adds a number of important features that give insight into the runtime state of the application. The library contains a number of autoconfigurations that add and configure the various endpoints to access the runtime monitoring data and health of the application. Those endpoints all share a common context path: /actuator. To expose any other endpoints besides /info and /health, we need to explicitly expose them by setting the management.endpoints.web.exposure.include=* property. When the value is set to *, it will expose all of the endpoints. The following endpoints are available to aid us in getting an insight into the application runtime state and configuration:
  • /env: This endpoint enables us to query the application about all of the environment variables that the application has access to via the environment implementation, which we have seen earlier. It is very useful when you need to debug a particular issue and want to know a value of any given configuration property. If we access the endpoint by going to http://localhost:8080/actuator/env, we will see a number of different configuration sections, for example, the class path resource [tomcat.https.properties], applicationConfig: [classpath:/application.properties], commonsConfig, systemEnvironment, systemProperties, and others. They all represent an instance of an individual PropertySource implementation that is available in the environment and depending on their place in the hierarchy, may or may not be used to provide the value resolution at the runtime. To find out exactly which entry is used to resolve a particular value, for example, for the book.count.rate property, we can query it by going to the http://localhost:8080/actuator/env/book.counter.rate URL. By default, we should get 10,000 as a result unless, of course, a different value was set via the system environment or command-line arguments as an override. If you really want to dig deep into the code, the EnvironmentEndpoint class is responsible for handling the logic behind this capability.
  • /configprops: This endpoint provides you with an insight into the settings of the various configuration property objects, such as our WebConfiguration.TomcatSslConnectorProperties starter. It is slightly different from the /env endpoint as it provides insight into the configuration object bindings. If we open the browser to go ...

Inhaltsverzeichnis