Spring Boot / Spring Cloud(十一)

104. What is spring boot?

In the big family of Spring framework, many derivative frameworks have been produced, such as Spring, SpringMvc framework, etc. The core content of Spring is inversion of control (IOC) and dependency injection (DI). The so-called inversion of control is not a technology, but It is an idea. In terms of operation, it refers to creation in the spring configuration file. Dependency injection means that the spring container provides resources for an object of the application, such as reference objects, constant data, and so on.

SpringBoot is a framework, a brand new programming specification, which simplifies the use of the framework. The so-called simplification refers to the simplification of a large number of and cumbersome configuration files required in many frameworks of Spring, so SpringBoot is a framework that serves the framework , The scope of service is to simplify configuration files.

105. Why use spring boot?

Spring Boot makes coding easy

Spring Boot使配置变简单

Spring Boot使部署变简单

Spring Boot使监控变简单

Spring的不足

12345678

106. What is the spring boot core configuration file?

Spring Boot provides two commonly used configuration files:

  • properties file
  • yml file

107. What types of spring boot configuration files are there? What is the difference between them?

Spring Boot provides two commonly used configuration files, namely the properties file and the yml file. Compared with the properties file, the yml file is younger and has many pitfalls. It can be said that Cheng Ye Xiao He defeat Xiao He, yml uses spaces to determine the hierarchical relationship, so that the configuration file structure is clear, but it will also destroy the hierarchical relationship due to insignificant spaces.

108. What are the ways to achieve hot deployment of spring boot?

There are two ways to implement SpringBoot hot deployment:

①. 使用spring loaded

Add the following code to the project:

<build>
        <plugins>
            <plugin>
                <!-- springBoot编译插件-->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <dependencies>
                    <!-- spring热部署 -->
                    <!-- 该依赖在此处下载不下来,可以放置在build标签外部下载完成后再粘贴进plugin中 -->
                    <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>springloaded</artifactId>
                        <version>1.2.6.RELEASE</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

12345678910111213141516171819

After adding, you need to use the mvn command to run:

First find the Edit configurations in IDEA, and then perform the following operations: (click on the "+" in the upper left corner, then select maven, the right panel will appear, enter the command as shown in the red line, and you can name the command ( Named here as MvnSpringBootRun))

Insert picture description hereClick save and it will appear in the IDEA project running part, click the green arrow to run
Insert picture description here
②. Use spring-boot-devtools

Add dependencies in the project's pom file:

 <!--热部署jar-->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-devtools</artifactId>
 </dependency>

123456

Then: use shift+ctrl+alt+"/" (shortcut key in IDEA) to select "Registry" and then check compiler.automake.allow.when.app.running

109. What is the difference between jpa and hibernate?

  • JPA Java Persistence API is the standard ORM interface of Java EE 5 and part of the ejb3 specification.
  • Hibernate, a very popular ORM framework today, is an implementation of JPA, but its function is a superset of JPA.
  • The relationship between JPA and Hibernate can be simply understood as JPA is the standard interface and Hibernate is the implementation. So how does Hibernate realize this relationship with JPA. Hibernate is mainly implemented through three components, hibernate-annotation, hibernate-entitymanager and hibernate-core.
  • Ibernate-annotation is the basis of Hibernate's support for annotation configuration. It includes standard JPA annotation and Hibernate's own special function annotation.
  • hibernate-core is the core implementation of Hibernate, which provides all the core functions of Hibernate.
  • hibernate-entitymanager implements standard JPA, which can be regarded as an adapter between hibernate-core and JPA. It does not directly provide ORM functions, but encapsulates hibernate-core so that Hibernate conforms to JPA specifications.

110. What is spring cloud?

Literally, Spring Cloud is a framework dedicated to distributed systems and cloud services.

Spring Cloud is a new member of the entire Spring family and an inevitable product of the recent hot cloud services.

Spring Cloud provides developers with tools to quickly build some common patterns in distributed systems. For example,
Insert picture description here
using Spring Cloud, developers can implement services and applications of these patterns out of the box. These services can run in any environment, including distributed environments, as well as developers’ own laptops and various hosting platforms.

111. What is the function of the spring cloud circuit breaker?

Hystrix is ​​used in Spring Cloud to implement the circuit breaker function. The circuit breaker can prevent an application from trying to perform an operation multiple times, that is, it is likely to fail, allowing it to continue without waiting for failure recovery or wasting CPU cycles, and it determines the The failure is permanent. The circuit breaker mode also enables the application to detect whether the fault has been resolved, and if the problem appears to have been corrected, the application can try to call the operation.

Circuit breakers increase stability and flexibility to provide stability to a system, while the system recovers from a fault, and minimizes the impact of this fault on performance. It can help quickly reject an operation that is likely to fail, instead of waiting for the operation to time out (or not return) request, in order to maintain the system's response time. If the circuit breaker increases the time of each change of state event, this information can be used to monitor the health of the components of the system protected by the circuit breaker, or to alert the administrator when the circuit breaker trips to be in the open state.

112. What are the core components of spring cloud?

①. Service discovery-Netflix Eureka

A RESTful service used to locate middle-tier services running in the AWS region (Region). It consists of two components: Eureka server and Eureka client. The Eureka server is used as a service registration server. Eureka client is a java client used to simplify the interaction with the server, as a polling load balancer, and provide failover support for services. Netflix uses another client in its production environment, which provides weighted load balancing based on traffic, resource utilization, and error status.

②. Load balancing on the customer service side-Netflix Ribbon

Ribbon, mainly provides client-side software load balancing algorithms. The Ribbon client component provides a series of complete configuration options, such as connection timeout, retry, retry algorithm, etc. Ribbon has built-in pluggable and customizable load balancing components.

③. Circuit breaker-Netflix Hystrix

The circuit breaker can prevent an application from trying to perform an operation multiple times, that is, it is likely to fail, allowing it to continue without waiting for the failure to recover or wasting CPU cycles, and it determines that the failure is permanent. The circuit breaker mode also enables the application to detect whether the fault has been resolved. If the problem seems to have been corrected, the application can try to call the operation.

④. Service gateway——Netflix Zuul

Similar to nginx, reverse proxy function, but netflix has added some features to cooperate with other components.

⑤. Distributed configuration-Spring Cloud Config

This is still static and needs to be used with Spring Cloud Bus to implement dynamic configuration updates.

Spring Cloud (Basic)

Spring Cloud is an ordered collection of a series of frameworks.
Spring Cloud does not repeatedly manufacture wheels, it just combines the relatively mature service frameworks that are currently developed by various companies and can withstand practical tests.
Re-encapsulation through the Spring Boot style shields the complex configuration and implementation principles, and finally leaves a set of distributed system development toolkits that are simple, easy to understand, easy to deploy, and easy to maintain for developers.
It uses Spring Boot's development convenience to cleverly simplifies the development of distributed system infrastructure, such as service discovery registration, configuration center, message bus, load balancing, circuit breakers, data monitoring, etc., all can be done in Spring Boot development style To one-click launch and deployment.
The official website of the Spring Cloud project: https://spring.io/projects/spring-cloud

Comparison of Spring Cloud and Dubbo

Both Spring Cloud and Dubbo are effective tools for implementing microservices.
Dubbo only implements service governance, and Spring Cloud sub-projects cover many components under the microservice architecture.
Dubbo uses the RPC communication protocol, Spring Cloud uses RESTful to complete the communication, and Dubbo is slightly more efficient than Spring Cloud.

summary:

Microservice is to split each module of the project into an architecture design style that can be run, deployed, and tested independently.
Spring company integrates components commonly used in microservice architectures of other companies, and uses SpringBoot to simplify its development and configuration. Called Spring Cloud
Spring Cloud and Dubbo are both effective tools for implementing microservices. Dubbo performance is better, and Spring Cloud is more comprehensive.

Spring Cloud service governance

Eureka consists of two components: Eureka Server (Registration Center) and Eureka Client (Service Provider, Service Consumer).

There are 4 parts of
eureka configuration server: eureka's server configuration
client: eureka's client configuration
instance: eureka's instance configuration
dashboard: eureka's web console configuration

Consul

Consul is developed by HashiCorp based on the Go language and supports multi-data center, distributed and highly available service publishing and registration service software.
Used to realize the service discovery and configuration of distributed systems.
It is also relatively simple to use. It has natural portability (supports Linux, windows and Mac OS X); the installation package contains only one executable file, which is convenient for deployment.
Official website address: https://www.consul.io

Nacos

Nacos (Dynamic Naming and Configuration Service) is an open source project of Alibaba in July 2018.
It focuses on the field of service discovery and configuration management and is dedicated to helping you discover, configure and manage microservices. Nacos supports the discovery, configuration and management of almost all mainstream types of "services".
In one sentence, Nacos = Spring Cloud Registration Center + Spring Cloud Configuration Center.
Official website: https://nacos.io/
Download address: https://github.com/alibaba/nacos/releases

Ribbon client load balancing

Ribbon is a client load balancing tool based on HTTP and TCP provided by Netflix.
Ribbon has two main functions:
simplifying remote calls and
load balancing

Ribbon can be used to simplify the remote call of RestTemplate

Ribbon is responsible for the balancing strategy:
Random: RandomRule
Polling: RoundRobinRule
Minimum Concurrency: BestAvailableRule
Filtering: AvailabilityFilteringRule
Response Time: WeightedResponseTimeRule
Polling Retry: RetryRule
Performance Availability: ZoneAvoidanceRule

Feign declarative service call

Feign is a declarative REST client, which uses interface-based annotations, which is very convenient for client configuration.
Feign was originally provided by Netflix, but it did not support SpringMVC annotations. It was later packaged by SpringCloud and supported SpringMVC annotations, making it easier for users to accept.

Feign quick start

Introduce open-feign dependency on the consumer side
Write Feign call interface
Add @EnableFeignClients annotation to the startup class to enable Feign function
Test call

The bottom layer of Feign relies on Ribbon to achieve load balancing and remote calls.
Ribbon defaults to a 1 second timeout.

Feign can only record debug level log information.

Hystrix fuses

Hystix is ​​a latency and fault-tolerant library open sourced by Netflix to isolate access to remote services and third-party libraries to prevent cascading failures (avalanche).
Avalanche: A service failure that causes the service of the entire link to fail.

Hystix main functions
​ Isolation

  1. Thread pool isolation

  2. Semaphore isolation

    Downgrade

    Hystix downgrade: when the service is abnormal or the call timed out, the default data will be returned

    Fuse

    The Hystrix fusing mechanism is used to monitor the invocation of microservices. When the failure reaches a predetermined threshold (20 failures in 5 seconds), the circuit breaker will be opened and all requests will be rejected until the service returns to normal.

    Hystrix provides the Hystrix-dashboard function to monitor the running status of microservices in real time.
    But Hystrix-dashboard can only monitor one microservice.
    Netflix also provides Turbine for aggregate monitoring.

    Limiting

Gateway

The gateway is the entrance of the system, which encapsulates the internal structure of the application and
provides unified services for the client . Some common logic that has nothing to do with the business itself can be implemented here,
such as authentication, authentication, monitoring, caching, and load balancing. , Traffic control, routing and forwarding, etc.
In the current gateway solutions, there are Nginx + Lua, Netflix Zuul, Spring Cloud Gateway, etc.

Gateway supports the filter function, intercepts requests or responses, and completes some common operations.
Gateway provides two filter methods: "pre" and "post"
pre filters, which are executed before forwarding, and can be used for parameter verification, authorization verification, traffic monitoring, log output, protocol conversion, etc.
The post filter is executed before the response. It can modify the response content, response headers, log output, traffic monitoring, etc.
Gateway also provides two types of filters,
GatewayFilter: local filters, for a single route
GlobalFilter: global filters, for all routes

GlobalFilter The global filter does not need to be configured in the configuration file. It is loaded when the system is initialized and applied to each route.
The core functions of Spring Cloud Gateway are also accomplished through built-in global filters.
Customize the global filter step:
define the class to implement the GlobalFilter and Ordered interfaces,
copy the method and
complete the logic processing

Config Distributed Configuration Center

Spring Cloud Config solves the management and maintenance of multi-environment configuration files in distributed scenarios.
Benefits:
Centralized management of configuration files
Different configurations in different environments, dynamic configuration update When
configuration information changes, the configuration information can be updated to the service without restarting

Bus message bus

Spring Cloud Bus uses lightweight message middleware to connect distributed nodes, which can be used to broadcast configuration file changes or service monitoring and management. The key idea is that the message bus can monitor and control microservices, and it can also communicate between applications.
Spring Cloud Bus optional message middleware includes RabbitMQ and Kafka.

RabbitMQ provides 6 working modes: simple mode, work queues, Publish/Subscribe mode, Routing mode, Topics topic mode, RPC remote call mode (remote call, not really MQ; no introduction).

Stream message driver

Spring Cloud Stream is a framework for building message-driven microservice applications.
Stream solves the problem of developers using message middleware unconsciously. Because Stream further encapsulates message middleware, it can achieve code level unawareness of middleware, and even dynamically switch middleware, making the development of microservices With a high degree of decoupling, the service can focus more on its own business processes.
Spring Cloud Stream currently supports two messaging middleware RabbitMQ and Kafka

The application built by Spring Cloud Stream and the message middleware are related through the binder. The binder acts as an isolation for the application. It makes the implementation details of different message middleware transparent to the application.
Binding is that we bind the application and the binder of the spring cloud stream through configuration. Output
: send message Channel, built-in Source interface
input: receive message Channel, built-in Sink interface

Sleuth+Zipkin link tracking

Spring Cloud Sleuth is actually a tool that can track the process of a user request in the entire distributed system. By capturing these tracking data, you can build a view of the entire call chain of the microservice. This is a key tool for debugging and monitoring microservices. . Time
-consuming analysis
Visualizing errors
Link optimization
Zipkin is an open source project of Twitter. It is dedicated to collecting service timing data to solve the delay problem in the microservice architecture, including data collection, storage, search and display.

SpringBoot

SpringBoot provides a quick way to use Spring. Based on the idea that conventions are better than configuration, developers don’t have to switch their thinking between configuration and logic business, and they devote themselves to the coding of logic business, which greatly greatly Improve the efficiency of development and shorten the project cycle to a certain extent. In April 2014, Spring Boot 1.0.0 was released. One of Spring's top projects (https://spring.io).

SpringBoot features:

1) Automatic configuration The automatic configuration of
Spring Boot is a process at runtime (more precisely, when the application starts). Many factors are considered before deciding which should be used for Spring configuration and which should not be used. This process is done automatically by SpringBoot.

2) Start-up dependency
Start-up dependency is essentially a Maven project object model (Project Object Model, POM), which defines transitive dependencies on other libraries. Together, these things support a certain function.
Simply put, the initial dependency is to pack the coordinates with a certain function together and provide some default functions.

3) Auxiliary function
Provides some non-functional features that are common in large-scale projects, such as embedded server, security, indicators, health detection, external configuration, etc.

Spring Boot is not an enhancement of Spring functionality, but provides a quick way to use Spring.

SpringBoot provides a way to quickly develop Spring projects, rather than enhancing Spring functions.

Disadvantages of Spring:
cumbersome configuration and cumbersome
dependency

SpringBoot function:
automatic configuration,
initial dependency: dependency transfer,
auxiliary function

SpringBoot configuration

SpringBoot is based on conventions, so many configurations have default values, but if you want to replace the default configuration with your own configuration, you can use application.properties or application.yml (application.yaml) for configuration.

properties:

server.port=8080

fr:

server:

port: 8080

SpringBoot provides 2 types of configuration files: properteis and yml/yaml

Default configuration file name: application

The priority in the same directory is: properties> yml> yaml

YAML

The full name of YAML is YAML Ain't Markup Language. YAML is an intuitive data serialization format that can be recognized by computers, and is easy to be read by humans, easy to interact with scripting languages, and can be imported by different programming language programs that support the YAML library, such as: C/C++, Ruby, Python, Java, Perl, C#, PHP, etc. YML files are data-centric, which is more concise than the traditional xml method.
YAML file extension can use .yml or .yaml.

YAML: Basic syntax

Case-sensitive
Data values ​​must have spaces in front of them as separators.
Use indentation to indicate hierarchical relationships
. Tab key is not allowed when indenting, only spaces are allowed (the number of spaces corresponding to tabs in each system may be different, leading to confusion in the hierarchy).
The number of indented spaces is not important, as long as the elements of the same level are aligned to the left

"# means a comment. From this character to the end of the line, it will be ignored by the parser."

Insert picture description here
Insert picture description here
Insert picture description here

YAML: Summary

1) Configuration file type
properties: same as before
yml/yaml: pay attention to spaces
2) yaml: concise, data-centric
basic syntax
case sensitive
Data values ​​must have spaces in front of them,
use spaces as separators to indent the hierarchical relationship, the same Indentation means the same level
Data format
Object
Array: Use "-" to indicate each element of the array
Scalar
Parameter reference
${key}

Profile-summary

1) The profile is used to configure the dynamic switching function in different environments.
2) Profile configuration mode
Multi-profile file mode: Provide multiple configuration files, each representing a kind of environment.
application-dev.properties/yml development environment
application-test.properties/yml test environment
application-pro.properties/yml production environment
yml multi-document mode:
use in yml — separate different configurations
3) profile activation mode
configuration file: reconfiguration Configuration in the file: spring.profiles.active=dev
Virtual machine parameters: specify in VM options: -Dspring.profiles.active=dev
Command line parameters: java –jar xxx.jar --spring.profiles.active=dev

Internal configuration loading sequence

When the Springboot program is started, the configuration file will be loaded from the following location:
file:./config/: the /config directory under the
current project file:./: the root directory of the current project
classpath:/config/: classpath's /config directory
classpath :/: the root directory of the classpath

The loading order is the order above, and the attributes configured with high priority will take effect

@Import annotation

@Enable* The bottom layer relies on @Import annotation to import some classes, and classes imported using @Import will be loaded into the IOC container by Spring. And @Import provides 4 usages:
import Bean
import configuration class
import ImportSelector implementation class. Generally used to load the class in the configuration file to
import the ImportBeanDefinitionRegistrar implementation class.

@EnableAutoConfiguration annotation

The @EnableAutoConfiguration annotation uses @Import(AutoConfigurationImportSelector.class) internally to load the configuration class.

Configuration file location: META-INF/spring.factories. This configuration file defines a large number of configuration classes. When the SpringBoot application starts, these configuration classes will be automatically loaded.
Not all beans will be initialized in the configuration class. Use Condition to load the Bean that meets the condition

Java monitoring mechanism

The monitoring mechanism of SpringBoot is actually an encapsulation of the event monitoring mechanism provided by Java.
The event monitoring mechanism in Java defines the following roles:
Event: Event, an object inheriting the java.util.EventObject class
Event source: Source, any object Object
listener: Listener, an object that implements the java.util.EventListener interface

SpringBoot monitoring mechanism

SpringBoot will call back several listeners when the project starts. We can implement these listener interfaces and complete some operations when the project starts.
ApplicationContextInitializer, SpringApplicationRunListener, CommandLineRunner, ApplicationRunner

Guess you like

Origin blog.csdn.net/xghchina/article/details/114955592