Spring Boot 2.0 Cookbook - Second Edition
Alex Antonov
- English
- ePUB (mobile friendly)
- Available on iOS & Android
Spring Boot 2.0 Cookbook - Second Edition
Alex Antonov
About This Book
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.
Frequently asked questions
Information
Health Monitoring and Data Visualization
- 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
Writing custom health indicators
How to do it...
- 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') ... }
- 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:
- 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:
- 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 ] } } }
- 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
- We will also add rootProject.name='BookPub-ch7' to the settings.gradle file located in the root directory of our project.
- 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:
- 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.
- 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.
- 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(); } } }
- 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})
- 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; }
- 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...
- /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 ...