Foreword: SpringBoot notes in station B crazy God talk Java, Portal
UP is nice, the course is vivid, welcome to support.
1, What is micro service
- Overall deployment: it is difficult for the change of each module not to affect other modules, resulting in a long change cycle. The expansion needs to be expanded as a whole rather than partially.
- At present, there is no unified and standard definition of microservices in the industry.
- But generally speaking, microservice architecture is an architecture mode, or an architecture style. Its length divides a single application into a group of small services. Each service runs in its own independent process. Services coordinate and configure with each other to provide final value for users. Services communicate with each other through lightweight communication mechanism (HTTP), Each service is built around a specific business and can be independently deployed to the production environment. In addition, a unified and centralized service management mechanism should be avoided as far as possible. For a specific service, an appropriate language and tool (Maven) should be selected to build it according to the business context, There can be a very lightweight centralized management to coordinate these services, services can be written in different languages, or different data stores.
- The core of microservicing is to split the traditional one-stop application into one service according to the business and completely decouple it. Each microservice provides a service with a single business function. One service does one thing. From a technical point of view, it is a small and independent processing process. The concept of similar process can be started or destroyed independently, Have their own independent database.
1.1 advantages of microservice
- The principle of single responsibility;
- Each service is cohesive and small enough, and the code is easy to understand, so that it can focus on a specified business function or business requirement;
- Development is simple and efficient. A service may be dedicated to only one thing;
- Microservices are loosely coupled;
- Microservices can be developed in different languages. Use different databases according to different needs;
1.2 disadvantages of microservice
- Complex distributed system
- Data consistency problem
- Difficult operation and maintenance
2, Spring cloud getting started overview
2.1 what is spring cloud
- Spring Cloud is a microservice framework. Compared with RPC frameworks such as Dubbo, Spring Cloud provides a complete set of distributed system solutions.
- Spring Cloud encapsulates multiple open source components of the microservice infrastructure framework Netflix, and realizes the integration with the cloud platform and Spring Boot development framework.
- Spring Cloud provides a simple development method for microservice architecture development involving configuration management, service governance, circuit breaker mechanism, intelligent routing, micro agent, control bus, one-time token, global consistency lock, leader election, distributed session, cluster state management and other operations.
- Spring Cloud provides developers with tools to quickly build distributed systems. Developers can quickly start services or build applications, and can quickly connect with cloud platform resources.
2.2 relationship between springcloud and SpringBoot
-
SpringBoot focuses on KAISU's convenient development of individual micro services;
-
SpringCloud is a microservice coordination and management framework that focuses on the overall situation. It integrates and manages individual microservices developed by SpringBoot, and provides integrated services among microservices: configuration management, service discovery, circuit breaker, routing, proxy, event stack, global lock, decision-making campaign, distributed session, etc;
-
SpringBoot can be used independently of SpringCloud to develop projects, but SpringCloud is inseparable from SpringBoot and belongs to dependency relationship;
-
SpringBoot focuses on the rapid and convenient development of individual micro services, and SpringCloud focuses on the overall service governance framework;
RPC has two cores:
Communication and serialization
2.3 Dubbo and SpringCloud technology selection
[external chain picture transfer failed. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-7vm6UAV3-1641400359603)(en-resource://database/1001:1)]
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-DLOfXFy2-1641400359603)(en-resource://database/1005:1)]
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-hD1bktv9-1641400359604)(en-resource://database/1007:2)]
- Spring Cloud abandons Dubbo's RPC communication and adopts HTTP based REST
3, Spring cloud rest learning environment construction: Service Provider
The Consumer consumer (Client) calls the service provided by the Provider (Server) through REST.
- RestTemplate... We can call it directly! Register in Spring (address: url, entity: map, class responsetype), provide a variety of convenient methods to access remote http services, and a simple Restful service template~
3.1 resrful style
Based on the above explanations, let's summarize what a RESTful architecture is:
(1) Each URI represents a resource;
(2) Between the client and the server, transfer some kind of presentation layer of this resource;
(3) The client operates the server-side resources through four HTTP verbs to realize "presentation layer state transformation".
3.2 URI and URL
3.2.1URI
URI, Uniform Resource Identifier (URI), means that every available resource on the web, such as HTML document, image, video clip, program, etc., is identified by a URI.
Structure of URI: ① naming mechanism of resource; ② The host name where the resource is stored; ③ The name of the resource itself;
(Note: This is only the naming method of general URI resources. Anything that can uniquely identify resources is called URI. The above three together are sufficient and unnecessary conditions for URI)
3.2.2URL
URL s are a subset of URI s. It is the abbreviation of Uniform Resource Locator, which is translated as "Uniform Resource Locator".
The format of the URL consists of three parts:
① The first part is the agreement (or service mode).
② The second part is the host IP address (sometimes including port number) where the resource is stored.
③ The third part is the specific address of host resources, such as directory and file name.
3.2.3 difference between URI and URL
uri can be considered only the number of identification, similar to the ID number, and url is the ID card address + name.
As long as the URI can uniquely identify the resource, the URL gives the access method of its resource based on the URI.
4, Eureka service registry
4.1 what is Eureka
- Netflix follows the API principles when it comes to Eureka
- Eureka is a sub module of Netflix and one of the core modules. Eureka is a REST based service. It is used to locate services to realize service discovery and failover in the cloud middleware layer. Service registration and discovery are very important for microservices. With service registration and discovery, you can access services only by using the service identifier without modifying the service invocation configuration file, The function is similar to Dubbo's registry, such as Zookeeper
4.2 Eureka basic architecture
- Spring cloud encapsulates the Eureka module developed by Netflix to realize service registration and discovery (compared with Zookeeper).
- Eureka adopts the C-S architecture design. Eureka server is the server of service registration function. It is the service registration center.
- Other microservices in the system use Eureka's client to connect to Eureka server and maintain heartbeat connection. In this way, the maintenance personnel of the system can monitor whether each micro service in the system is running normally through EurekaServer. Some other modules of spring cloud (such as Zuul) can discover other micro services in the system through EurekaServer and execute relevant logic.
Comparison and Dubbo area
- Eureka consists of two components: Eureka Server and Eureka Client
- Eureka Server provides service registration. After each node is started, it will be registered in Eureka Server. In this way, the service registry in Eureka Server will store the information of all class service nodes, and the information of service nodes can be seen intuitively in the interface
- Eureka Client is a Java client, which is used to simplify the interaction of Eureka Server. The client also has a built-in load balancer using polling load algorithm. After the application starts, a heartbeat will be sent to EurekaServer (the default cycle is 30 seconds). If Eureka Server does not receive the heartbeat of a node in multiple heartbeat cycles, Eureka Server will remove the service node from the service registry (the default cycle is 90s)
- Three roles
1. Eureka Server: provides service registration and discovery
2. Service Provider: the service producer registers its own services in Eureka so that the service consumer can find them
3. Service Consumer: the Service Consumer. Get the registered service list from Eureka to find the consumer service
4.3 Eureka service construction
- Eureka-server
1. Create the springcloud-eureka-7001 module
2. Add POM XML configuration
<!--Guide Package~--> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server --> <!--Import Eureka Server rely on--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> <version>1.4.6.RELEASE</version> </dependency> <!--Hot deployment tool--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> </dependencies>
3,application.yml
server: port: 7001 # Eureka configuration eureka: instance: # Instance name of Eureka server hostname: 127.0.0.1 client: # Indicates whether to register yourself with Eureka Registry (this module itself is a server, so it is not required) register-with-eureka: false # If the fetch registry is false, it means that it is the registry and the client is changed to true fetch-registry: false # Eureka monitoring page~ service-url: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
4. Main startup class
/** * @Auther: csp1999 * @Date: 2020/05/18/10:26 * @Description: After startup, access http://127.0.0.1:7001/ */ @SpringBootApplication // @The startup class of EnableEurekaServer server can accept others to register~ @EnableEurekaServer public class EurekaServer_7001 { public static void main(String[] args) { SpringApplication.run(EurekaServer_7001.class,args); } }
Display after access:
- eureka-client
1. Import Eureca dependencies
<!--Eureka rely on--> <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> <version>1.4.6.RELEASE</version> </dependency>
2. Eureca configuration added in application
# Eureka configuration: configure the service registry address eureka: client: service-url: defaultZone: http://localhost:7001/eureka/
3. Add the @ EnableEurekaClient annotation to the main startup class
/** * @Auther: csp1999 * @Date: 2020/05/17/22:09 * @Description: Startup class */ @SpringBootApplication // @Enable Eureka client enables Eureka client annotation and automatically registers the service with the registry after the service is started @EnableEurekaClient public class DeptProvider_8001 { public static void main(String[] args) { SpringApplication.run(DeptProvider_8001.class,args); } }
- EureKa's self-protection mechanism: living is better than dying
In a word, if a micro service is unavailable at a certain time, eureka will not clean it immediately, but will still save the information of the micro service!
- By default, if the eureka server does not receive the instance heartbeat within a certain period of time, the instance will be deleted from the registry (the default is 90 seconds). However, if a large number of instance heartbeats are lost in a short period of time, the eureka server's self-protection mechanism will be triggered. For example, during development and testing, microservice instances need to be restarted frequently, However, we rarely restart the eureka server together (because the eureka Registry will not be modified during development). When the number of heartbeats received in one minute decreases significantly, the protection mechanism will be triggered.
4.4 Eureka: cluster environment configuration
1. Initialization
New springcloud-eureka-7002 and springcloud-eureka-7003 modules
1. POM XML add dependency (same as springcloud-eureka-7001)
<dependencies> <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server --> <!--Import Eureka Server rely on--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> <version>1.4.6.RELEASE</version> </dependency> <!--Hot deployment tool--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency> </dependencies>
2.application.yml configuration (same as springcloud-eureka-7001)
server: port: 7003 # Eureka configuration eureka: instance: hostname: localhost # Instance name of Eureka server client: register-with-eureka: false # Indicates whether to register yourself with Eureka Registry (this module itself is a server, so it is not required) fetch-registry: false # If fetch registry is false, it indicates that it is the registry service-url: # Monitoring page~ # Override Eureka's default port and access path -- > http://localhost:7001/eureka/ defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
3. Main startup class (same as springcloud-eureka-7001)
/** * @Auther: csp1999 * @Date: 2020/05/18/10:26 * @Description: After startup, access http://127.0.0.1:7003/ */ @SpringBootApplication // @The startup class of EnableEurekaServer server can accept others to register~ public class EurekaServer_7003 { public static void main(String[] args) { SpringApplication.run(EurekaServer_7003.class,args); } }
2. Cluster members are interrelated
Configure some custom native names, find the native hosts file and open it
Complete application under springcloud-eureka-7001 YML is as follows
server: port: 7003 #Eureka eureka: instance: hostname: localhost # Instance name of Eureka server client: register-with-eureka: false # Indicates whether to register yourself with the eureka registry fetch-registry: false # If fetch registry is false, it indicates that it is the registry service-url: # Monitoring page defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
4.5 comparison and Zookeeper differences
1. Review CAP principles
RDBMS (MySQL\Oracle\sqlServer) ===> ACID
NoSQL (Redis\MongoDB) ===> CAP
2. What is acid?
A (Atomicity)
C (Consistency)
I (Isolation)
D (Durability)
3. What is cap?
C (Consistency) strong consistency
A (Availability)
P (Partition tolerance)
Three in two of CAP: CA, AP, CP
1. What is CAP?
C (Consistency) strong consistency A (Availability) availability P (Partition tolerance) partition fault tolerance
2. The core of CAP theory
A distributed system cannot meet the three requirements of consistency, availability and partition fault tolerance at the same time
According to the principle of CAP, NoSQL database is divided into three categories: meeting CA principle, meeting CP principle and meeting AP principle
CA: single point cluster. Systems that meet consistency and availability usually have poor scalability
CP: a system that meets consistency and partition fault tolerance. Generally, the performance is not particularly high
AP: a system that meets the requirements of availability and partition fault tolerance. Generally, it may have lower requirements for consistency
3. What's better about Eureka than Zookeeper?
- Zookeeper guarantees CP - > systems that meet consistency and partition fault tolerance, and generally have low performance
When querying the service list from the registry, we can tolerate that the registry returns the registration information a few minutes ago, but we can't receive the service and directly down it. In other words, the service registration function requires higher availability than consistency. However, a situation occurs in zookeeper. When the master node loses contact with other nodes due to network failure, the remaining nodes will re elect leaders. The problem is that the election leader takes too long, 30-120s, and the entire zookeeper cluster is unavailable during the election, which leads to the paralysis of the registration service during the election. - Eureka guarantees that AP - > systems that meet availability and partition fault tolerance may generally have lower requirements for consistency
Eureka understands this, so it gives priority to ensuring availability in design. Eureka's nodes are equal. The failure of several nodes will not affect the work of normal nodes, and the remaining nodes can still provide registration and query services. When registering with an Eureka client, if the connection fails, it will automatically switch to other nodes. As long as one Eureka is still there, the availability of the registration service can be maintained, but the information found may not be up-to-date,
Eureka all nodes are equal. If several nodes hang up, it will not affect the work of normal nodes, and the remaining nodes can still provide registration and query services;
Eureka is not removing services that should expire because they haven't received a heartbeat for a long time from the registration list
5, Ribbon: load balancing (client based)
5.1 what is Ribbon
- Spring Cloud Ribbon is a set of client-side load balancing tools based on Netflix Ribbon.
- In short, Ribbon is an open source project released by Netflix. Its main function is to provide software load balancing algorithms for clients and connect Netflix's middle tier services together. The Ribbon client component provides a series of complete configuration items, such as connection timeout, Retry, etc. To put it simply, list all the machines behind the LoadBalancer (LB: load balancer for short) in the configuration file. The Ribbon will automatically help you connect these machines based on certain rules (such as simple polling, random connection, etc.). We can also easily use Ribbon to implement a custom load balancing algorithm!
5.2 integrated Ribbon
springcloud-consumer-dept-80 to POM Add Ribbon and Eureka dependencies to XML
<!--Ribbon--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> <version>1.4.6.RELEASE</version> </dependency> <!--Eureka: Ribbon Need from Eureka What can I get from the service center--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> <version>1.4.6.RELEASE</version> </dependency>
In application Configure Eureka in the YML file
server: port: 80 # Eureka configuration eureka: client: register-with-eureka: false # Do not register yourself with Eureka service-url: defaultZone: http://eureka7003.com:7003/eureka/,http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
The main startup class is annotated with @ EnableEurekaClient to open Eureka
@SpringBootApplication @EnableEurekaClient //When the microservice starts, we can load our custom Ribbon class @RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT", configuration = KuangRule.class) public class DeptConsumer_80 { public static void main(String[] args) { SpringApplication.run(DeptConsumer_80.class, args); } }
Custom Spring configuration class: configbean Java configuration load balancing to implement RestTemplate
@Configuration // @Configuration --- spring applicationContext.xml public class ConfigBean { /** * IRule: * RoundRobinRule round-robin policy * RandomRule Random strategy * AvailabilityFilteringRule : It will filter out, trip, access the failed service ~, and poll the rest~ * RetryRule : The service ~ will be obtained according to the polling first. If the service acquisition fails, it will be performed within the specified time and try again */ //Configure load balancing to implement RestTemplate @Bean @LoadBalanced //Ribbon public RestTemplate getRestTemplate() { return new RestTemplate(); } }
Modify the controller: deptconsumercontroller java
//Ribbon: the address here should be a variable accessed by the service name //private static final String REST_URL_PREFIX = "http://localhost:8001"; private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";
5.3 load balancing using Ribbon
1. Create two new service providers: springcloud-provider-dept-8003 and springcloud-provider-dept-8002
2. Refer to springcloud-provider-dept-8001 to add POM for the other two clouds XML dependency, mybatis under resourcece and application YML configuration, Java code
3. Start all service tests (determine the number of services to start according to your computer configuration), and access http://eureka7001.com:7002/ View results
Test access http://localhost/consumer/dept/list At this time, the service provider 8003 is accessed randomly
6, Feign load balancing (based on server)
6.1 Feign introduction
Feign is a declarative Web Service client, which makes it easier to call between microservices, similar to the controller calling service. Spring cloud integrates Ribbon and Eureka, and can use Feigin to provide a load balanced http client.
Just create an interface and add annotations~
Feign, mainly the community version, is used to interface oriented programming. This is the norm for many developers. There are two methods for invoking microservice access
1. Microservice name [ribbon]
2. Interface and notes [feign]
Under the implementation of Feign, we only need to create an interface and configure it by annotation (similar to the Mapper annotation on Dao interface in the past, and now a Feign annotation on a micro service interface), so as to complete the interface binding to the service provider, which simplifies the development of automatically encapsulating the service call client when using Spring Cloud Ribbon.
6.2 use steps of feign
1. Create the springcloud consumer fdept feign module
2. Fill in POM xml
<!--Feign Dependence of--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> <version>1.4.6.RELEASE</version> </dependency>
3,DeptController.java
import com.kuang.springcloud.pojo.Dept; import com.kuang.springcloud.service.DeptClientService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class DeptController { @Autowired private DeptClientService service; @RequestMapping("/consumer/dept/add") public boolean add(Dept dept) { return service.addDept(dept); } @GetMapping("/consumer/dept/get/{id}") public Dept get(@PathVariable("id") Long id) { return service.queryById(id); } @RequestMapping("/consumer/dept/list") public List<Dept> list() { return service.queryAll(); } }
4. Comparing Feign and Ribbon, the former shows the characteristics of interface oriented programming, the code looks more refreshing, and the Feign call method is more in line with our previous programming habit of calling the Service layer by the Controller layer when we were doing SSM or sprnboot projects!
@SpringBootApplication @EnableEurekaClient // feign client annotation, and specifies the package to be scanned and the configuration interface DeptClientService @EnableFeignClients(basePackages = {"com.kuang.springcloud"}) // Remember not to add this annotation, otherwise 404 cannot be accessed //@ComponentScan("com.haust.springcloud") public class FeignDeptConsumer_80 { public static void main(String[] args) { SpringApplication.run(FeignDeptConsumer_80.class, args); } }
5. Write spring cloud API module
Add fegin dependency
<!--Feign Dependence of--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> <version>1.4.6.RELEASE</version> </dependency>
6. Write service interface
// @FeignClient: Micro service client annotation, value: specify the name of the micro service, so that the Feign client can directly find the corresponding micro service @FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT") public interface DeptClientService { @GetMapping("/dept/get/{id}") public Dept queryById(@PathVariable("id") Long id); @GetMapping("/dept/list") public Dept queryAll(); @GetMapping("/dept/add") public Dept addDept(Dept dept); }
6.3 what are the similarities and differences between feign and Ribbon?
- Ribbon is a load balancer based on HTTP and TCP clients
It can configure the ribbon server list on the client, and then poll the request to balance the load. - Feign is an improvement based on the Ribbon. It is a more convenient http client. In the way of interface, only one interface needs to be created, facing the interface; Then add an annotation above to define the methods of other services to be called as abstract methods without building http requests. Then, it is like calling the method call of its own project without feeling that it is calling the remote method, which makes it very easy to write the client. The @ Mapper annotation is similar to mybatis.
7, Hystrix: Service fuse
There are dozens of dependencies for applications in complex distributed architecture, and each dependency will inevitably fail at some time!
7.1 service avalanche
When calling between multiple microservices, suppose microservice A calls microservice B and microservice C, and microservice B and microservice C call other microservices, which is the so-called "fan out". If the call response time of A microservice on the fan out link is too long or unavailable, the call to microservice A will occupy more and more system resources, resulting in system crash, The so-called "avalanche effect".
These applications may also lead to increased delays between services, tight backup queues, threads and other system resources, resulting in more cascading failures of the whole system. These all mean that failures and delays need to be isolated and managed to achieve the failure of a single dependency without affecting the operation of the whole application or system.
7.2 what is Hystrix?
Hystrix is an open source library used to deal with the delay and fault tolerance of distributed systems. In distributed systems, many dependencies inevitably fail to call, such as timeout, exception, etc. hystrix can ensure that when a dependency fails, it will not lead to the failure of the whole system service, avoid cascading failures, and improve the elasticity of distributed systems.
"Circuit breaker" itself is a kind of switching device. When a service unit fails, it returns a service expected and processable alternative response (FallBack) to the caller through the fault monitoring of the circuit breaker (similar to a blown fuse), rather than waiting for a long time or throwing an exception that cannot be handled by the calling method, This can ensure that the thread of the service caller will not be occupied unnecessarily for a long time, so as to avoid the spread and even avalanche of faults in the distributed system.
7.3 what can hystrix do?
Service degradation, service fusing, service current limiting, near real-time monitoring
When everything is OK, the request flow can be as follows
When there is a potentially blocking service in many back-end systems, it can block the entire user request:
7.4 service fuse
Circuit breaker mechanism is a microservice link protection mechanism to win avalanche effect.
When a microservice of the fan out link is unavailable or the response time is too long, the service will be degraded, which will fuse the call of the microservice of the node and quickly return the wrong response information. After detecting that the microservice call response of the node is normal, restore the call link.
The following problems can be solved by the service provider:
1. When the dependent object is unstable, it can achieve the purpose of rapid failure;
2. After a fast failure, it can dynamically test whether the dependent object is restored according to a certain algorithm.
example
Create a new springcloud provider Dept hystrix-8001 module and copy the POM in springcloud provider Dept – 8001 xml
<!--Import Hystrix rely on--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> <version>1.4.6.RELEASE</version> </dependency>
Adjust yml profile
server: port: 8001 # mybatis configuration mybatis: type-aliases-package: com.kuang.springcloud.pojo config-location: classpath:mybatis/mybatis-config.xml mapper-locations: classpath:mybatis/mapper/*.xml # spring configuration spring: application: name: springcloud-provider-dept datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/db01?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: 123 # Eureka's configuration, where is the service registered eureka: client: service-url: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ instance: instance-id: springcloud-provider-dept-hystrix-8001 # Modify the default description information on eureka ip-address: true # info configuration info: app.name: kaungshen-springcloud company.name: blog.kuangstudy.com
Modify controller
import com.kuang.springcloud.pojo.Dept; import com.kuang.springcloud.service.DeptService; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController public class DeptController { @Autowired private DeptService deptService; @GetMapping("/dept/get/{id}") @HystrixCommand(fallbackMethod = "hystrixGet") public Dept queryById(@PathVariable("id") Long id) { Dept dept = deptService.queryById(id); if (dept == null) { throw new RuntimeException("id => " + id + ",The user does not exist or cannot be found"); } return dept; } //alternative method public Dept hystrixGet(@PathVariable("id") Long id) { return new Dept().setDeptno(id) .setDename("id => " + id + "No corresponding information, null--@Hystrix") .setDb_source("no this database in mysql"); } }
Add the support annotation @ enablercircuitbreaker to the main startup class
//Startup class @SpringBootApplication @EnableEurekaClient //After the service is started, it is automatically registered in Eureka @EnableDiscoveryClient //Service discovery @EnableCircuitBreaker //Add support for fusing public class DeptProviderHystrix_8001 { public static void main(String[] args) { SpringApplication.run(DeptProviderHystrix_8001.class, args); } //Add a Servlet @Bean public ServletRegistrationBean hystrixMetricsStreamServlet() { ServletRegistrationBean registrationBean = new ServletRegistrationBean(new HystrixMetricsStreamServlet()); registrationBean.addUrlMappings("/actuator/hystrix.stream"); return registrationBean; } }
7.5 service degradation
7.5.1 what is service degradation
Service degradation means that when the server pressure increases sharply, some services and pages are not processed strategically or handled in a simple way according to the actual business conditions and traffic, so as to release server resources to ensure the normal or efficient operation of core business. To put it bluntly, it is to give system resources to high priority services as much as possible. For example, when double 11 is active, all services unrelated to the transaction are downgraded, such as viewing ant deep forest, viewing historical orders, etc.
Introductory case
Create a new degraded configuration class deptclientservicefallbackfactory. In the service package under the springcloud API module java
/** * @Auther: csp1999 * @Date: 2020/05/20/9:18 * @Description: Hystrix Service degradation~ */ @Component public class DeptClientServiceFallBackFactory implements FallbackFactory { @Override public DeptClientService create(Throwable cause) { return new DeptClientService() { @Override public Dept queryById(Long id) { return new Dept() .setDeptno(id) .setDname("id=>" + id + "There is no corresponding information. The client provides degraded information. The service has been shut down") .setDb_source("no data~"); } @Override public List<Dept> queryAll() { return null; } @Override public Boolean addDept(Dept dept) { return false; } }; } }
Specify the degraded configuration class DeptClientServiceFallBackFactory in DeptClientService
@Component //Register in spring container //@FeignClient: Micro service client annotation, value: specify the name of the micro service, so that the Feign client can directly find the corresponding micro service @FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT",fallbackFactory = DeptClientServiceFallBackFactory.class)//fallbackFactory specifies the degraded configuration class public interface DeptClientService { @GetMapping("/dept/get/{id}") public Dept queryById(@PathVariable("id") Long id); @GetMapping("/dept/list") public List<Dept> queryAll(); @GetMapping("/dept/add") public Boolean addDept(Dept dept); }
Enable demotion in the springcloud consumer dept feign module:
server: port: 80 # Eureka configuration eureka: client: register-with-eureka: false # Do not register yourself with Eureka service-url: # Access one of the three registries at random defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ # Enable degraded feign hystrix feign: hystrix: enabled: true
7.5.2 difference between service fusing and degradation
- Service fusing - > server: a service timeout or exception causes fusing ~, which is similar to a fuse (Self Fusing)
- Service degradation - > client: considering the overall website request load, when a service is blown or closed, the service will no longer be called. At this time, on the client, we can prepare a FallBackFactory and return a default value (default value). It will lead to a decline in the overall service, but at least it can be used, which is better than hanging up directly.
The triggering reasons are different. Service fusing is generally caused by a service (downstream service) fault, and service degradation is generally considered from the overall load; The levels of management objectives are different. Fusing is actually a framework level process, and each micro service needs to be (without hierarchy), while degradation generally needs to have hierarchy for the business (for example, degradation generally starts from the most peripheral services)
7.6 dashboard flow monitoring
Create a new springcloud consumer hystrix dashboard module – >
Add dependency – > Add main startup class – > Add monitoring
<!--Hystrix rely on--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> <version>1.4.6.RELEASE</version> </dependency> <!--dashboard rely on--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId> <version>1.4.6.RELEASE</version> </dependency> <!--Ribbon--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> <version>1.4.6.RELEASE</version> </dependency> <!--Eureka--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> <version>1.4.6.RELEASE</version> </dependency> <!--Entity class+web--> <dependency> <groupId>com.haust</groupId> <artifactId>springcloud-api</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--Hot deployment--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency>
Main startup class
@SpringBootApplication // Open Dashboard @EnableHystrixDashboard public class DeptConsumerDashboard_9001 { public static void main(String[] args) { SpringApplication.run(DeptConsumerDashboard_9001.class,args); } }
Add the following code to the main startup class under the springcloud provider Dept hystrix-8001 module to add monitoring
@SpringBootApplication @EnableEurekaClient //The startup class of EnableEurekaClient client automatically registers the service with the registry after the service is started public class DeptProvider_8001 { public static void main(String[] args) { SpringApplication.run(DeptProvider_8001.class,args); } //Add a Servlet @Bean public ServletRegistrationBean hystrixMetricsStreamServlet(){ ServletRegistrationBean registrationBean = new ServletRegistrationBean(new HystrixMetricsStreamServlet()); //Accessing this page is the monitoring page registrationBean.addUrlMappings("/actuator/hystrix.stream"); return registrationBean; } }
8, Zull routing gateway
8.1 what is Zull
Zull includes two main functions: Request Routing (for jump) and filtering:
The routing function is responsible for forwarding external requests to specific micro service instances, which is the basis for realizing the unified entrance of external access, while the filter function is responsible for intervening in the request processing process, which is the basis for realizing request verification, service aggregation and other functions. Zuul and Eureka integrate, register zuul as an application under Eureka service governance, and obtain messages of other services from Eureka, that is, access to micro services in the future is obtained through zuul jump.
Introductory case
Create a new springcloud zuul module and import dependencies
<dependencies> <!--Import zuul rely on--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> <version>1.4.6.RELEASE</version> </dependency> <!--Hystrix rely on--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> <version>1.4.6.RELEASE</version> </dependency> <!--dashboard rely on--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix-dashboar</artifactId> <version>1.4.6.RELEASE</version> </dependency> <!--Ribbon--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> <version>1.4.6.RELEASE</version> </dependency> <!--Eureka--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> <version>1.4.6.RELEASE</version> </dependency> <!--Entity class+web--> <dependency> <groupId>com.haust</groupId> <artifactId>springcloud-api</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--Hot deployment--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> </dependencies>
application.yml
server: port: 9527 spring: application: name: springcloud-zuul eureka: client: service-url: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ instance: instance-id: zuul9527.com # Modify the default description information on eureka prefer-ip-address: true info: app.name: kuang-springcloud company.name: blog.kuangstudy.com # Routing gateway configuration zuul: routes: mydept.serviceId: springcloud-provider-dept mydept.path: /mydept/** # You can no longer use this path to access. Ignore: ignore "*" to hide all the real paths of microservices ignored-services: "*" prefix: /kuang # Prefix of public settings
Main startup class
/** * @Auther: csp1999 * @Date: 2020/05/20/20:53 * @Description: Zull Routing gateway master startup class */ @SpringBootApplication @EnableZuulProxy // Open Zuul public class ZuulApplication_9527 { public static void main(String[] args) { SpringApplication.run(ZuulApplication_9527.class,args); } }
Test:
The routing function is responsible for forwarding external requests to specific micro service instances, which is the basis for realizing the unified entrance of external access, while the filter function is responsible for intervening in the request processing process, which is the basis for realizing request verification, service aggregation and other functions.
It provides three functions: agent + routing + filtering!
9, Spring Cloud Config distributed configuration
spring cloud config provides centralized external support for microservices in the microservice architecture. The configuration server provides a centralized external configuration for all links of different microservice applications.
9.1 what is the spring cloud config distributed configuration center?
- spring cloud config is divided into two parts: server and client.
- The server is also called distributed configuration center. It is an independent micro service application, which is used to connect to the configuration server and provide the client with access interfaces such as obtaining configuration information, encryption and decryption information.
- The client manages application resources and business-related configuration content through the specified configuration center, and obtains and loads configuration information from the configuration center at startup. The configuration server uses git to store configuration information by default, which is helpful for version management of environment configuration. The GIT client tool can be used to manage and access the configuration content conveniently.
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-pYSm9y8m-1641400359612)(en-resource://database/1028:1)]
9.2 what can the spring cloud config distributed configuration center do?
- Centralized management profile
- Different environments, different configurations, dynamic configuration updates, and deployment by environment, such as / dev /test /prod /beta /release
- The configuration is dynamically adjusted during operation. It is no longer necessary to write configuration files on each service deployed machine. The service will uniformly pull and configure its own information from the configuration center
- When the configuration changes, the service does not need to restart, it can sense the configuration changes and apply the new configuration
- Expose the configuration information in the form of REST interface
9.3 configuration
server: port: 3344 spring: application: name: springcloud-config-server # Connection code cloud remote warehouse cloud: config: server: git: # Note that it is https, not ssh uri: https://gitee.com/cao_shi_peng/springcloud-config.git # You can connect to git through config server to access its resources and configuration~ # If this configuration is not added, the error Cannot execute request on any known server will be reported: the address of the Eureka server connection is incorrect # Or directly comment out the eureka dependency. eureka is temporarily unavailable here eureka: client: register-with-eureka: false fetch-registry: false
@Value("${}") can obtain the property value defined in the corresponding property file.
@Value(#{""}) when getting properties of other beans or calling methods of other beans, as long as the bean (Beab_A) can access the called bean(Beab_B), that is, either BEAB_ A and BEAB_ B is in the same container, or BEAB_ The container of B is BEAB_ The parent container of a's container.