39
Spring Boot - A Microframework for Microservices Nilanjan Roy

Spring boot for buidling microservices

Embed Size (px)

Citation preview

Page 1: Spring boot for buidling microservices

Spring Boot - A Microframework for

Microservices

Nilanjan Roy

Page 2: Spring boot for buidling microservices

What is Spring Boot ?

• Focuses attention at a single point (as opposed to large collection of spring-* projects)

• A tool for getting started very quickly with Spring• Common non-functional requirements for a "real" application• Exposes a lot of useful features by default• Gets out of the way quickly if you want to change defaults

Page 3: Spring boot for buidling microservices

What is Spring Boot

Page 4: Spring boot for buidling microservices

How Does it help microservices ?• You are going to write more than one microservice• That means you are going to do this a lot….

– Declare dependencies– Configure Spring– Configure logging– Load properties file– Setup monitoring– Add Security– Talk to a database– Add metrics

Page 5: Spring boot for buidling microservices

Spring Boot Modules

Page 6: Spring boot for buidling microservices

Spring Boot Modules• Spring Boot - main library supporting the other parts of Spring Boot• Spring Boot Autoconfigure -

single @EnableAutoConfiguration annotation creates a whole Spring context

• Spring Boot Starters - a set of convenient dependency descriptors that you can include in your application.

• Spring Boot CLI - compiles and runs Groovy source as a Spring application

• Spring Boot Actuator - common non-functional features that make an app instantly deployable and supportable in production

• Spring Boot Tools - for building and executing self-contained JAR and WAR archives

• Spring Boot Samples - a wide range of sample apps

Page 7: Spring boot for buidling microservices

Spring Boot Starter POMs

Page 8: Spring boot for buidling microservices

Spring Boot Actuator: Production-ready features

Page 9: Spring boot for buidling microservices

Gaining application insight with Actuator

• Spring Boot Actuator adds several helpful management endpoints to a Spring Boot-based application. These endpoints include

• GET /autoconfig —Explains the decisions made by Spring Boot when applying autoconfiguration

• GET /beans —Catalogs the beans that are configured for the running application

• GET /configprops —Lists all properties available for configuring the properties of beans in the application with their current values

• GET /dump —Lists application threads, including a stack trace for each thread

Page 10: Spring boot for buidling microservices

Gaining application insight with the Actuator

• GET /env —Lists all environment and system property variables available to the application context

• GET /env/{name} —Displays the value for a specific environment or property variable

• GET /health —Displays the current application health • GET /info —Displays application-specific information • GET /metrics —Lists metrics concerning the application, including running

counts of requests against certain endpoints • GET /metrics/{name} —Displays metrics for a specific application metric

key • POST /shutdown —Forcibly shuts down the application • GET /trace —Lists metadata concerning recent requests served through the

application, including request and response headers

Page 11: Spring boot for buidling microservices

Extending The Actuator

Page 12: Spring boot for buidling microservices

Extending The Actuator

Page 13: Spring boot for buidling microservices

Monitoring MicroServices

Page 14: Spring boot for buidling microservices

Monitoring MicroServices

Page 15: Spring boot for buidling microservices

Customizing Monitoring Endpoints• We can change how those endpoints are exposed

using application.properties

– management.port=8081 - you can expose those endpoints on port other than the one application is using .

– management.address=127.0.0.1 - you can only allow to access by IP address (localhost here).

– management.context-path=/actuator - allows you to have those endpoints grouped under specified context path rather than root, i.e. /actuator/health.

– endpoints.health.enabled=false - allows to enable/disable specified endpoint by name, here /health is disabled.

Page 16: Spring boot for buidling microservices

Customizing Monitoring Endpoints• We can change if an endpoint is enabled, if it is considered sensitive and even

its id.• Following entry in the application.properties that changes the sensitivity and id

of the beans endpoint and also enables shutdown.endpoints.beans.id=springbeans endpoints.beans.sensitive=false endpoints.shutdown.enabled=true

• By default, all endpoints except for shutdown are enabled. If you prefer to specifically “opt-in” endpoint enablement you can use the endpoints.enabled property. For example, the following will disable all endpoints except for info:

endpoints.enabled=false endpoints.info.enabled=true

Page 17: Spring boot for buidling microservices

Securing Monitoring Endpoints<dependency> <groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-security</artifactId> </dependency>• Disable basic security in application.properties, so that it leaves only the

sensitive Actuator endpoints secured and leaves the rest open for access:– security.basic.enabled=false

• Set up a new username, or a password if you don't want it to be different on each start:– security.user.name=admin – security.user.password=new_password

• In case you're using the security features across the application and decided to secure those endpoints yourself, you can disable default security for Actuator:– management.security.enabled=false

Page 18: Spring boot for buidling microservices

Custom Healthchecks• Besides checking if the application is UP or DOWN, which is done by

default, you can add checks for things like database connectivity or MQ status etc. @Component public class MyHealth implements HealthIndicator {

@Override public Health health() {

int errorCode = check(); // perform some specific health check if (errorCode != 0)

{ return Health.down().withDetail("Error Code", errorCode).build();

} return Health.up().build(); }

}

Page 19: Spring boot for buidling microservices

Measure Everything with Metrics

Page 20: Spring boot for buidling microservices

Emitting your own Metrics

• GaugeService :– A service that can be used to submit a named double value for storage

and analysis. – For instance, the value submitted here could be a method execution

timing result, and it would go to a backend that keeps a histogram of recent values for comparison purposes.

• CounterService :– Increment , decrement or reset an integer value (e.g. number of times

an error was thrown)

Page 21: Spring boot for buidling microservices

Storing Metrics

Page 22: Spring boot for buidling microservices

Logging with Spring Boot

Page 23: Spring boot for buidling microservices

Logging with Spring Boot• Spring Boot uses Commons Logging for all internal logging, but

leaves the underlying log implementation open. Default configurations are provided for Java Util Logging,Log4J and Logback. In each case there is console output and file output (rotating, 10 Mb file size).

• By default, If we use the ‘Starter POMs’, Logback will be used for logging. Appropriate Logback routing is also included to ensure that dependent libraries that use Java Util Logging, Commons Logging, Log4J or SLF4J will all work correctly.

Page 24: Spring boot for buidling microservices

Spring Boot AutoConfiguration

• Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, If HSQLDB is on your classpath, and you have not manually configured any database connection beans, then it will auto-configure an in-memory database.

• You need to opt-in to auto-configuration by adding the @EnableAutoConfiguration or @SpringBootApplication annotations to one of your @Configurationclasses.

• Disabling AutoConfiguration@Configuration @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class MyConfiguration { }

Page 25: Spring boot for buidling microservices

Understanding AutoConfiguration

Page 26: Spring boot for buidling microservices

Behind the Scene

• There are two parts to it :

1) List of files which has to be considered as configuration classes

2) When these should be applied

Page 27: Spring boot for buidling microservices

Behind the Scene• @EnableAutoConfiguration" is a spring-boot(autoconfigure) annotation

which is handled by org.springframework.boot.autoconfigure.EnableAutoConfigurationImportSelector.

• In "EnableAutoConfigurationImportSelector", it uses "org.springframework.core.io.support.SpringFactoriesLoader#loadFactoryNames" from spring-core to load configurations whose key is "org.springframework.boot.autoconfigure.EnableAutoConfiguration".

• This method reads "META-INF/spring.factories" from jar files.(multiple jar files can have "spring.factories" and when they have same key, comma delimited values will be merged.)

Page 28: Spring boot for buidling microservices

Understand @Conditional

Page 29: Spring boot for buidling microservices

Understand “Twelve-Factor App” style configuration

Page 30: Spring boot for buidling microservices

Understand “Twelve-Factor App” style configuration

• Spring Boot builds upon propertySource

• It allows you to externalize your configuration so you can work with the same application code in different environments. You can use properties files, YAML files, environment variables and command-line arguments to externalize configuration.

• Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values, properties are considered in the following order:

Page 31: Spring boot for buidling microservices

Understand “Twelve-Factor App” style configuration

Page 32: Spring boot for buidling microservices

Understand “Twelve-Factor App” style configuration

Set the active Spring profiles :• Profile-specific application properties outside of your packaged jar

(application-{profile}.properties and YAML variants)• Profile-specific application properties packaged inside your jar

(application-{profile}.properties and YAML variants)– Usually set through system profile (spring.profiles.active) or an OS environment variable

(SPRING_PROFILES_ACTIVE).e.g. $ java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar

or it can be set in application.properties : spring.profiles.active=production

Page 33: Spring boot for buidling microservices

Spring FrameWork profiles for Multiple Environments

Page 34: Spring boot for buidling microservices

Relaxed Bindings

Page 36: Spring boot for buidling microservices

Understand “Twelve-Factor App” style configuration

• @ConfigurationProperties

– A way to map properties to POJO– Type Safe– IDE Support– Can be validated with @Valid

Page 37: Spring boot for buidling microservices

Creates Runnable Fat JARs

Page 38: Spring boot for buidling microservices

The executable jar file structure

example.jar | +-META-INF | +-MANIFEST.MF +-org | +-springframework | +-boot | +-loader | +-<spring boot loader classes> +-com | +-mycompany | + project | +-YouClasses.class +-lib +-dependency1.jar +-dependency2.jar

Page 39: Spring boot for buidling microservices

References & Further readings

• http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/

• http://cloud.spring.io/spring-cloud-netflix/