Play with the Spring family bucket (part 1)

Playing with the Spring Family Bucket (2)

9. Re-understand Spring Boot

9.1 Introduction to Spring Boot Components

  • Spring Boot

    1. What it is: It’s a faster and better application to help you build a Spring framework.
    2. What it is not:
      1. Not the application server
      2. It’s not a specification like Java EE
      3. Not a code generator
      4. Not an updated version of the Spring Framework
  • Spring Boot features

    1. Easy to create Spring applications that can run on their own
    2. Directly embed Tomcat, Jetty, or Undertow
    3. Simplifies the project’s build configuration
    4. Provides automatic configuration for Spring and third-party libraries
    5. Provides production grade features
    6. No code generation or XML configuration is required
  • The four cores of Spring Boot

    • Auto Configuration – Auto Configuration
    • Starter Dependency – Starter Dependency
    • CLI – Spring Boot CLI
    • Actuator

9.2 Understanding the implementation principles of automatic configuration

  • Automatic configuration
    1. Spring Boot applications are automatically configured based on added JAR dependencies
    2. Spring-boot-autoconfiguration
  • Enabling Automatic Configuration
    1. @EnableAutoConfiguration
      1. exclude = Class
        []
    2. @SpringBootApplication

      The annotations on the startup class already have the auto-configuration annotations above.

  • The principle of automatic configuration is as follows:
    • Conditional notes:
  • Learn about automatic configuration
    • Observe the automatic configuration result
      • debug
    • ConditionEvaluatinReportLoggingListener
      • Positive matches
      • Negative matches
      • Exclusions
      • Unconditional classes

9.3 Start your own automatic configuration

  • Conditional notes extended family
    • Conditional annotation: @Conditional
    • Such conditions:
      • @ConditionalOnClass
      • @ConditionalOnMissingClass
    • Attribute conditions
      • @ConditionalOnProperty
    • Bean conditional annotations:
      • @ConditionalOnBean
      • @ConditionalOnMissingBean
      • @ConditionalOnSingleCandidate
    • Resource conditions:
      • @ConditionalOnResource
    • Web Application Conditions
      • @ConditionalOnWebApplication
      • @ConditionalOnNotWebApplication
    • Other conditions
      • @ConditionalOnExpression
      • @ConditionalOnJava
      • @ConditionalOnJndi
  • Conditional annotation code demo:

9.4 How can I Quickly Implement Automatic Configuration functions in Earlier Versions of Spring

  • Requirements and Problems:

  • Core solution:

  • Two extension points for Spring:

  • Some customizations about beans:

  • Some common operations:

  • A few tips on Maven dependency management

    • Know your dependencies:
      • mvn dependency:tree
      • IDEA Maven Helper plugin
    • Exclude specific dependencies
      • exclusion
    • Unified Management of Dependencies
      • dependencyManagement
      • Bill of Materials – bom

9.5 Understand the starting dependency and its implementation principle

  • Starter Dependencies
    • Direct to function
    • One site gets all related dependencies, no more copy and paste
  • The official Starters
    • spring-boot-starter-*

    These dependencies can be imported directly through automatic configuration and Maven’s dependencies.

9.6 Customizing your own startup dependencies

  • Main Contents:
    • Autoconfigure module, which contains automatic configuration code
    • The starter module, which contains the dependencies pointing to the auto-configuration module and other related dependencies
  • Naming method:
    • xxx-spring-boot-autoconfigure
    • xxx-spring-boot-starter
  • Some considerations
    1. Do not use spring-boot as a prefix for dependencies
    2. Do not use the spring-boot configuration namespace
    3. The starter adds only necessary dependencies
    4. Declare a dependency on spring-boot-starter

9.7 Dig into the configuration loading mechanism of Spring Boot

  • Externalize the configuration load order

    Properties takes precedence over YML, and files are also top-down.

  • application.properties
    • ./config
    • . /
    • In the CLASSPATH/config
    • In the CLASSPATH /
  • Change the name or path:
    • spring.config.name
    • spring.config.location
    • spring.config.additional-location
  • Relaxed Binding
  • Example:

    The website address

9.8 Understand the PropertySource abstraction behind the configuration

  • PropertySource:
  • The @ ConfigurationProperties SpringBoot
    • Properties can be bound to structured objects
    • Support the Relaxed Binding
    • Support for safe type conversions
    • @EnableConfigurationProperties
  • Custom PropertySource
    • Main steps:
      1. Implement PropertySource
      2. Get PropertySources from Environment
      3. Add your own PropertySource to the appropriate place
    • Cutting position:
      • EnvironmentPostProcessor
      • BeanFactoryPostProcessor

X. Spring Boot in operation

10.1 Learning about Various Types of Spring Boot Actuators Endpoints

  • Actuator

    • purpose
      • Monitor and manage applications
    • Access mode:
      • HTTP
      • JMX
    • Rely on:
      • Spring-boot-starter-actuator
  • Some common endpoints

  • How can I access the Actuator Endpoint

  • How can I access the Actuator Endpoint

10.2 Customize your own Health Indicator

  • Spring Boot comes with the Health Indicator
  • Customize Health Indicators

10.3 Obtaining Operating Data from Micrometer

  • Official website Description:

  • Know the Micrometer

    • Features:
      • Multidimensional measure
        • Support the Tag
      • Preset large number of probes
        • Caching, class loaders, GC, CPU utilization, thread pools
      • Deep integration with Spring
  • Support a variety of monitoring systems:

  • Some core metrics:

  • Micrometer in Spring Boot 2.x

    This is explained in Chapter 57 of the Spring documentation

  • Customize metrics

10.4 Using Spring Boot Admin to Check the Running Status of the Program

  • Spring Boot Admin
  • Quick learning
  • Safety control:

10.5 How Can I Customize The Running Parameters of a Web Container

  • Embedded Web containers
  • Modifying container Configuration

10.6 How Can I Configure a Container to Support HTTP /2

  • Configuring HTTPS support:

  • Generating a certificate file:

  • Client HTTPS support

  • Configure HTTP/2 support:

  • Client HTTP/2 support:

10.7 How to Write Programs that Run on the CLI

  • Closing the Web Container
  • Common tools:

10.8 Learn the secrets behind executable Jars

  • Recognize the executable Jar

  • How to find the entry to the program:

  • One step further: directly runnable JARS

  • Some configuration items in the default script

10.9 How can I Package a Spring Boot Application as a Docker Image File

  • What is a Docker image?

    • A mirror is a static read-only template
    • The image contains instructions for building a Docker container
    • The mirror image is layered
    • Dockerfile is used to create the image
  • Dockerfile:

  • Build a Docker image using Maven

  • dockerfile-maven-plugin

  • Example of executing build code:

    1. Construction:
    2. After the build is complete, the image is generated:
    3. Run the built image using the docker command and print the log:

11. Overview of Spring Cloud and Cloud Native

11.1 Understanding microservices

  • Definition: Microservices are small, autonomous services that work together
  • Advantages of microservices:
    • Heterogeneity: language, storage…
    • Elasticity: If a component is unavailable, cascading faults will not occur
    • Individual services are not easy to scale, and multiple smaller services can be scaled on demand
    • Easy to deploy
    • Align with the organizational structure
    • composability
    • alternative
  • Without a silver bullet, microservices come at a cost:
    • The complexity of distributed systems
    • The complexity of development, testing, and so on
    • There are many o&M complexities, such as deployment and monitoring

11.2 How to Understand Cloud Native

  • Overview: Cloud native technologies enable organizations to build and run resilient scale-up applications in new dynamic environments such as public, private and hybrid clouds.
  • Cloud native application requirements:
  • The conversation:
    • Development and operations work together to deliver high quality software to serve customers
  • Continuous delivery:
    • Build, test, and release software faster, more often, and more consistently
  • The service:
    • Deploy the application as a set of small services
  • Container:
    • Provides higher efficiency than traditional VMS
  • Cloud Native Computing Foundation

    These are the open source projects for which it is better known

11.3 12-Factor App

  • THE TWELVE-FACTOR APP
    • Objective:
      1. Provide proven methodologies for building SaaS applications
      2. Suitable for the development of any language and back-end services applications
      3. 12factor.net/zh_cn/
  • 12 – the Factors
    • Benchmark code (Codebase)
      • One base code, multiple deployments
    • Dependencies
      • Explicitly declare dependencies
    • Configuration (Config)
      • Store the configuration in the environment

      Separate the configuration from the code

    • Backing Services
      • Think of backend services as additional resources
    • Build, Publish, Run
      • Strictly separate build and run
    • Processes
      • Run the application as one or more stateless processes
    • Port Bingding
      • Services are provided through port binding
    • Concurrency (Concurrentcy)
      • Extend through the process model
    • Disposability
      • Fast start and graceful end maximizes robustness
    • Dev/Prod Parity Development environment and online environment equivalence (Dev/Prod Parity)
      • Keep development, pre-release, and online environments as identical as possible
    • Logs
      • Think of logs as a stream of events
    • Admin Processes
      • Background administrative tasks run as one-off processes
  • Details:
    • One base code, multiple deployments:
    • Explicitly declare dependencies:

      You can use scanning tools to check for dependencies with the same name, dependency conflicts, and so on.

    • Strict separation of build and run:
    • Run the application as one or more stateless processes
    • Fast start and graceful end maximizes robustness

      Terminate as normally as possible. We do not accept new connections and close all thread tasks after SQL execution. We should log errors during sudden outages.

    • Keep development, pre-release, and online environments the same as much as possible:

11.4 Know the components of Spring Cloud

  • Introduction to Spring Cloud

  • Spring Cloud Component overview:

  • Key features of Spring Cloud

    1. Service discovery
    2. Service fusing
    3. Configure the service
    4. Service security
    5. The service gateway
    6. Distributed message
    7. Distributed tracking
    8. Various cloud platforms support
  • Version number rules for Spring Cloud

Xii. Service registration and discovery

12.1 Use Eureka as the service registry

  • Know the Eureka
  • Start a simple Eureka service locally
  • Register the service with Eureka Server
  • About the Bootstrap property

12.2 Accessing a Service Using SpringCloud Loadbalancer

  • How to obtain service address:

    It is better to use the latter, which is an abstraction and can be used in other registries.

  • Load Balancer Client
  • Code demo:

12.3 Accessing services Using Feign

  • Know Feign
  • Simple use of Feign
  • Customize Feign by configuration:
  • Some other Feign configurations:

12.4 Learn more about DiscoveryClient

  • The abstraction provided by Spring Cloud Commons
  • Automatic registration with Eureka server

12.5 Using Zookeeper as the Service Registry

  • Know the Zookeeper

  • Use Zookeeper as the registry

  • Problems with using Zookeeper as a registry

  • Start Zookeeper using Docker

12.6 Using Consul as a Service Registry

  • Introduction:
  • Know HashiCorp Consul
  • Use Consul to provide service discovery capabilities
  • Use Consul as the registry
  • Launch Consul using Docker

12.7 Using Nacos as a service registry

  • Know Nacos
  • Use Nacos as the registry
  • Start Nacos with Docker

12.8 How Can I Customize DiscoveryClient

  • Spring Cloud classes that you’ve worked with
  • Implement DiscoveryClient
  • Implement your own RibbonClient support

Xiii. Service fuse

13.1 Service Fusing Using Hystrix

  • Breaker mode:
  • Netflix Hystrix

13.2 How to Observe the Fusing Condition

  • How to observe?
    • Log: this log is printed when a fuse break occurs
    • The monitoring:
      • Report the fusing condition to the monitoring system
      • Provide fuse-related endpoints for third-party systems to pull information
  • Hystrix Dashboard
  • Aggregation cluster fuse breaker information:

It is better to be able to uniformly output the abnormal information in the monitoring system.

13.3 Implement service fusing and current limiting by Using Resilience4j

  • Alternatives to Hystrix

  • Add-ons:

  • The circuit breaker

  • Code examples:

    • Application code:
    • Configuration:
  • Bulkhead

    • Objective:
      • Prevent downstream dependencies from being hit by concurrent requests
      • Prevent serial failures
    • usage
      • BulkheadRegistry / BulkheadConfig
      • @bulkhead (name = “name “)
  • RateLimiter:

13.4 summary

  • Summary:

    Guava provides some useful methods and frameworks for using Java better

  • Wax-service: Use RateLimiter of Resilience4j for protection
  • customer-service:
    • Use Hystrix to fuse
    • Use Resilience4j for circuit breakers and concurrency control

Xiv. Service configuration

14.1 Git-based Configuration Center

  • Spring Cloud Config Server

    • Purpose: To provide an HTTP API for external configuration
    • Rely on:
      • spring-cloud-config-server
        • @EnableConfigServer
        • Support Git/SVN/Vault/JDBC
  • Using Git as backend storage:

  • Code examples:

    1. Add dependencies:
    2. Importing configuration:
    3. Annotate the startup class:

    When the last step is annotated, it is a Config Server!

  • Spring Cloud Config Client

    • Rely on:
      • spring-cloud-starter-config
    • Discovery Configuration Center
      • bootstrap.properties | yml
      • spring.cloud.config.fail-fast=true
      • By configuring
        • spring.cloud.config.uri=http://localhost:8888
      • Discovered through services:
        • spring.cloud.config.discovery.enabled=true
        • spring.cloud.config.discovery.service-id = configserver
    • Configuration refresh:
      • @RefreshScope
      • Endpoint-/actuator/refresh

14.2 Configuration Center Based on Zookeeper

  • Steps required to use the configuration center:
  • How to save data in Zookeeper?

    After an attribute is configured in Zookeeper, it takes precedence over the project.

14.3 Understand SpringCloud’s configuration abstractions in depth

  • Spring Cloud Config

    • Objective: To provide external configuration support in distributed systems
    • Implementation:
      • Similar to Environment and PropertySource in Spring applications
      • Add Spring Cloud Config’s PropertySource in context
  • Spring Cloud Config’s PropertySource

  • Spring Cloud Config Server

  • Spring Cloud Config Zookeeper

  • Configuration sequence:

    In the case of YML, the priority is from top to bottom, with the highest priority at the top

14.4 Configuration Center Based on Consul

  • Spring Cloud Consul Config setup steps:
  • How do I store data in Consul?
  • Configuration item Change:

    Installation tutorial can be baidu.

14.5 NacOS-based Configuration Center

  • Spring Cloud Alibaba Nacos Config
  • How do I store data in Nacos?
  • Configuration Screenshot:

14.6 summary

  • Several different configuration centers:
  • Ctrip Apollo
    • The official address
    • Features:
      1. Centrally manage configurations in different environments and clusters
      2. Configuration changes take effect immediately (hot release)
      3. Release management
      4. Gray released
      5. Authority management, release audit, operation audit
      6. Monitor client configuration information
      7. Provide open platform apis

Spring Cloud Stream

15.1 Learning about Spring Cloud Stream

  • Spring Cloud Stream

    • What is? It is a lightweight framework for building message-driven microservice applications
    • Features:
      • Declarative programming model
      • Introduce a variety of conceptual abstractions
        • Publish subscriptions, consumer groups, partitions
      • Support for multiple message-oriented middleware
        • The RabbitMQ, Kafka
  • Some of the core concepts of Spring Cloud Stream:

    • Consumer group: – For the same message, one consumer in each group receives the message
  • How do I send and receive messages

    • Production news:
      • Use the Send () method in MessageChannel
      • @SendTo
    • Consumer news:
      • @StreamListener
        • @Payload / @Headers / @Header
    • Other notes:
      • You can use Spring Integration

15.2 Accessing RabbitMQ through Spring Cloud Stream

  • Spring Cloud Stream support for RabbitMQ
    • Rely on:
      • Spring Cloud: spring-cloud-starter-stream-rabbit
      • Spring Boot: spring-boot-starter-amqp
    • Configuration:
  • Start RabbitMQ using Docker
    • The official guide
    • Obtain the image:
      docker pull rabbitmq
      Copy the code
      docker pull rabbitmq:3.7-management
      Copy the code
    • Run RabbitMQ images:
      docker run --name rabbitmq -d -p 5672:5672 -p 15672:15672 -e RABBITMQ_DEFAULT_USER=spring -e RABBITMQ_DEFAULT_PASS = spring rabbitmq:3.7-management
      Copy the code
  • Message flow through RabbitMQ:

15.3 Accessing Kafka through Spring Cloud Stream

  • Know the Apache Kafka

    • What is a Kafka
  • SpringCloud support for Kafka:

  • Start Kafka with Docker

  • Operation steps:

    1. Introducing dependencies:
    2. Configuration:
    3. Listening:
    4. Message sending:
  • Scheduled tasks in Spring

  • The event mechanism in Spring

15.4 summary

Xvi service link tracing

16.1 Using Dapper to Understand Link Governance

  • What are we looking at?
    • What services are available in the system?
    • What are the dependencies between services?
    • What is the execution path of a common request?
    • Whether the execution of each link is normal and time-consuming
  • Some terminology for Google Dapper
    • Span – Basic unit of work
    • Trace – A tree structure consisting of a set of spans
    • Annotation – Used to record events in time
      • cs – Client Sent
      • sr – Server Received
      • ss – Server Sent
      • cr – Client Received
  • Google Dapper:

16.2 Link Tracing using Spring Cloud Sleuth

  • Service governance capabilities provided by Spring Cloud
  • Start Zipkin with Docker
    • Official guidelines:
      • Hub.docker.com/r/openzipki…
      • [github.com/openzipkin/…].
    • Obtain the image:
      • docker pull openzipkin/zipkin
    • Run the Zipkin image:
      docker run --name zipkin -d -p 9411:9411 openzipkin/zipkin
      Copy the code

16.3 How Do I Trace Message Links

  • Trace messages with Spring Cloud Sleuth:
  • Enable Zipkin to receive messages via RabbitMQ:

16.4 What else is Governed besides links

  • What does service governance care about?
    • On the macro:
      1. Is the architecture design reasonable
      2. Which links are critical links
      3. Capacity watermark trend of a link
      4. Manage and audit system changes
    • Micro level:
      1. What does a system depend on
      2. What are the configurations of a system
      3. The subjective and objective qualities of a system

16.5 summary

  • Spring Cloud’s service governance features:
    • Borrowed from Google Dapper

    • Spring Cloud Sleuth

      • Zipkin
        • Web
        • RabbitMQ
      • We should care more
    • Waiter-service/customer-service

      • Add Web based embedding to Zipkin
    • barista-service

      • Added the ability to bury Zipkin points based on MQ
    • The final product:

      • Run the entire project through Docker

Useful words, click on favorites at any time to check oh ~