Crazy God said spring cloud learning notes - KuangStudy - article
1.1 learning premise
- Proficient in using SpringBoot microservice rapid development framework
- Learned about Dubbo + Zookeeper distributed Foundation
-
The configured memory of the computer is no less than 8g (my own is 16G)
-
Let's see the memory overhead diagram of multiple services after running:
-
1.2 article outline
Five components of Spring Cloud
- Service registration and discovery - Netflix Eureka
-
Load balancing:
- Client load balancing - Netflix Ribbon
- Server load balancing: - feign (it also depends on the Ribbon, but changes the call method resttemplet to Service interface)
- Circuit breaker - Netflix Hystrix
- Service gateway - Netflix Zuul
- Distributed configuration - Spring Cloud Config
1.3 common interview questions
1.1 what is micro service?
1.2 how do microservices communicate independently?
1.3 what are the differences between springcloud and Dubbo?
1.4 SpringBoot and SpringCloud, please talk about your understanding of them
1.5 what is service fusing? What is service degradation?
1.6 what are the advantages and disadvantages of microservices? Tell me about the pitfalls you encountered in project development
1.7 what are the micro service technology stacks you know? List one or two
1.8 Eureka and Zookeeper can provide the functions of service registration and discovery. Please tell us the difference between them
...
2. Overview of microservices
2.1 what is micro service?
What is micro service?
Microservice architecture is a popular architecture idea in recent years. It is difficult to sum up its concept.
What exactly is a micro service? We hereby quote Martin Fowler, chief scientist of ThoughtWorks, who put forward a paragraph in 2014:
Original text: Microservices
Sinicization: Microservices - Martin Flower - Captain & Cap - blog Park
- At present, there is no unified and standard definition of microservices in the industry.
- But generally speaking, microservice architecture is an architectural mode, or architectural 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.
From the perspective of Technology:
- The core of microservicing is to divide 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, and 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.
2.2 microservices and microservice architecture
Microservices
It emphasizes the size of the service. It focuses on a certain point. It is a service application that specifically solves a certain problem / provides landing corresponding services. In a narrow sense, it can be regarded as micro service projects in the IDEA or Moudel. In the IDEA tool, independent small Moudel developed by Maven is used. It specifically uses a small module developed by SpringBoot. Professional things are done by professional modules, and each module does one thing. The emphasis is on individuals, and each individual completes a specific task or function.
Microservice architecture
A new form of architecture was proposed by Martin Fowler in 2014.
Microservice architecture is an architecture mode. Its body length divides a single application into a group of small services. Services coordinate and cooperate with each other to provide final value for users. Each service runs in its own independent process. Lightweight communication mechanism * * (such as HTTP) is adopted between services to cooperate with each other. Each service is built around specific business and can be independently deployed to the production environment. In addition, unified and centralized service management mechanism should be avoided as far as possible. For a specific service, Appropriate languages and tools (such as Maven) * * should be selected according to the business context to build it.
2.3 advantages and disadvantages of microservices
advantage
- 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 can be developed independently by a small team, which only needs 2-5 developers;
- Microservices are loosely coupled and functionally meaningful services, which are independent in both development and deployment stages;
- The development of micro services using different languages;
- It is easy to integrate with third parties. Microservices allow easy and flexible integration and automatic deployment through continuous integration tools, such as jenkins, Hudson and bamboo;
- Microservices are easy to be understood, modified and maintained by a developer, so that small teams can pay more attention to their own work results and reflect their value without cooperation;
- Microservices allow the use and integration of the latest technologies;
- Microservices are just the code of business logic and will not be mixed with HTML, CSS or other interfaces;
- Each microservice has its own storage capacity. It can have its own database or a unified database;
shortcoming
- Developers need to deal with the complexity of distributed systems;
- Multi service operation and maintenance is difficult. With the increase of services, the pressure of operation and maintenance is also increasing;
- System deployment dependency;
- Communication cost between services;
- Data consistency;
- System integration test problems;
- Performance and monitoring issues;
2.4 what are the micro service technology stacks?
- |* * microservice technology entry * * landing technology|
- | -------------------- | ------------------------------------------------ |
- |Service development | SpringBoot, Spring, Spring MVC, etc|
- |Service configuration and management | Archaius of Netfix, Diamond of Alibaba, etc|
- |Service registration and discovery | Eureka, Consul, Zookeeper, etc|
- |Service call | Rest, PRC, gRPC|
- |Service fuses | Hystrix, Envoy, etc|
- |Load balancing | Ribbon, Nginx, etc|
- |Service interface call (simplified tool for client to call service) | Fegin, etc|
- |Message queue | Kafka, RabbitMQ, ActiveMQ, etc|
- |Service configuration center management | SpringCloudConfig, Chef, etc|
- |Service routing (API gateway) | Zuul et al|
- |Service monitoring | Zabbix, Nagios, Metrics, specifier, etc|
- |Full link tracking | Zipkin, Brave, Dapper, etc|
- |Data flow operation development package | spring cloud stream (encapsulating sending and receiving messages with Redis, Rabbit, Kafka, etc.)|
- |Time message stack | SpringCloud Bus|
- |Service deployment | Docker, OpenStack, Kubernetes, etc|
2.5 why spring cloud is chosen as the microservice architecture
-
Selection basis
- Overall solution and framework maturity
- Community heat
- Maintainability
- learning curve
-
What are the current micro service architectures used by major IT companies?
- Ali: dubbo+HFS
- JD: JFS
- Sina: Motan
-
Dangdang: DubboX
...
-
Comparison of micro Service Frameworks
-
|Function point / service framework | Netflix / springcloud | Motan | GRC | thri t | Dubbo / dubbox|
| --- | -------------- | --------—- | ----— | -- | ----- |
|Functional positioning | complete microservice framework | RPC framework, but it integrates ZK or consult to realize the basic service registration and discovery | RPC framework | RPC framework | service framework in cluster environment|
|Support Rest | yes, Ribbon supports multiple pluggable serial number options | no | no | no | no ||
|Support RPC | no | Yes (Hession2) | yes | yes | yes ||
|Support multiple languages | Yes (Rest form) | no | yes | yes | no|
|Load balancing | Yes (server zuul + client Ribbon), zuul service, dynamic routing, cloud load balancing Eureka (for middle tier server) | Yes (client) | no | no | Yes (client)|
|Configuration service | Netfix archhaius, Spring Cloud Config Server centralized configuration | Yes (provided by Zookeeper) | no | no ||
|Service call chain monitoring | Yes (zuul), zuul provides edge services, API gateway | no | no | no ||
|High availability / fault tolerance | Yes (server side Hystrix + client Ribbon) | Yes (client side) | no | no | Yes (client side)|
|Typical application case | Netflix | Sina | Google | Facebook ||
|Community activity | high | average | high | average | maintenance will resume after 2017, which was interrupted for 5 years before|
|Learning difficulty | medium | low | high | high | low|
|Document richness | high | average | average | high|
|Other | Spring Cloud Bus brings more management endpoints to our applications | support degradation | more companies develop and integrate GRC | IDL definition | practice within Netflix|
3. Introduction to spring cloud
3.1 what is spring cloud?
Spring official website: Spring | Home
3.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 between microservices: configuration management, service discovery, circuit breaker, routing, proxy, event stack, global lock, decision-making campaign, distributed session and so on;
- SpringBoot can be used independently of SpringCloud to develop projects, but SpringCloud cannot be separated from SpringBoot, which belongs to dependency;
- SpringBoot focuses on the rapid and convenient development of individual micro services, and SpringCloud focuses on the overall service governance framework;
3.3 Dubbo and SpringCloud technology selection
1. Distributed + service governance Dubbo
The current mature Internet architecture, application service splitting + message middleware
2. Comparison between Dubbo and spring cloud
Take a look at community activity:
Comparison results:
- | | Dubbo | SpringCloud |
- | ------ | ------------- | ---------------------------- |
- |Service registry | Zookeeper | Spring Cloud Netfilx Eureka|
- |Service call method | RPC | REST API|
- |Service monitoring | Dubbo monitor | spring boot admin|
- |Circuit breaker | imperfect | Spring Cloud Netfilx Hystrix|
- |Service gateway | none | Spring Cloud Netfilx Zuul|
- |Distributed configuration | none | Spring Cloud Config|
- |Service tracking | none | Spring Cloud Sleuth|
- |Message stack | none | Spring Cloud Bus|
- |Data stream | none | Spring Cloud Stream|
- |Batch tasks | none | spring cloud tasks|
The biggest difference: Spring Cloud abandons Dubbo's RPC communication and adopts HTTP based REST
Strictly speaking, these two methods have their own advantages and disadvantages. Although to some extent, the latter sacrifices the performance of service invocation, it also avoids the problems caused by the above-mentioned native RPC. Moreover, REST is more flexible than RPC. The dependence of service providers and callers only depends on one contract, and there is no strong dependence at the code level. This advantage is more appropriate in the current microservice environment that emphasizes rapid evolution.
Difference between brand machine and assembly machine
The difference between community support and renewal
**Summary: * * the two solve different problem domains: Dubbo is positioned as an RPC framework, while spring cloud aims at a one-stop solution under the microservice architecture.
3.4 what can spring cloud do?
- Distributed/versioned configuration
- Service registration and discovery
- Routing
- Service to service calls
- Load balancing configuration
- Circuit Breakers
- Distributed messaging
- ...
3.5 spring cloud Download
Official website: Redirecting...
The version number is a little special:
Instead of naming the version number by numerical number, SpringCloud uses the name of London underground station, and corresponds to the chronological order of the version according to the alphabet. For example, the earliest real version is Angel, the second real version is Brixton, followed by Camden, Dalston and Edgware. At present, the latest is the general stable version of Hoxton SR4 CURRENT GA.
Self study reference books:
- SpringCloud Netflix Chinese document: Spring Cloud Netflix Chinese document reference manual Chinese version
- SpringCloud Chinese API document (official document translation): Chinese version of Dalston cloud spring reference manual
- SpringCloud China Community: http://springcloud.cn/
- SpringCloud Chinese website: https://springcloud.cc
4. Construction of spring cloud rest learning environment: Service Provider
4.1 introduction
- We will use a Dept Department module as a general case of microservices. The Consumer consumer (Client) calls the services provided by the Provider (Server) through REST.
- Review the previous knowledge of Spring, Spring MVC, Mybatis, etc.
- Review of Maven's subcontracting module architecture.
- A simple Maven module structure is as follows:
- --App parent: an app parent aggregates many child projects (APP util \ app Dao \ app Web...)
- |-- pom.xml
- |
- |-- app-core
- ||---- pom.xml
- |
- |-- app-web
- ||---- pom.xml
- ......
A parent project has multiple Moudule sub modules
MicroServiceCloud has three sub modules under its parent project for the first time
- Microservicecloud API [encapsulated overall entity / interface / public configuration, etc.]
- microservicecloud-consumer-dept-80 [service provider]
- microservicecloud-provider-dept-8001 [serving consumers]
4.2 spring cloud version selection
Large Version Description
- |SpringBoot | SpringCloud | relationship|
- | ---------- | ----------------- | ---------------------------------- |
- | 1.2.x | Angel Version (angel) | compatible with springboot1 2x |
- | 1.3.x | Brixton Version (Brixton) | compatible with springboot1 3x, also compatible with springboot1 4x |
- | 1.4.x | Camden Version (Camden) | compatible with springboot1 4X, also compatible with springboot1 5x |
- | 1.5.x | Dalston Version (dorston) | compatible with springboot1 5x, incompatible with springboot2 0x |
- | 1.5.x | Edgware Version (edgwell) | compatible with springboot1 5x, incompatible with springboot2 0x |
- | 2.0.x | Finchley Version (Finchley) | compatible with springboot 2 0x, incompatible with springboot1 5x |
- | 2.1.x | Greenwich Version (Greenwich) ||
Actual development version relationship
- | spring-boot-starter-parent | | spring-cloud-dependencles | |
- |:--------------------------:| --------:|:-------------------------:|:--------:|
- |* * version number * * release date * * version number * * release date * *|
- | 1.5.2.RELEASE | 2017-03 | Dalston.RC1 | 2017-x |
- | 1.5.9.RELEASE | 2017-11 | Edgware.RELEASE | 2017-11 |
- | 1.5.16.RELEASE | 2018-04 | Edgware.SR5 | 2018-10 |
- | 1.5.20.RELEASE | 2018-09 | Edgware.SR5 | 2018-10 |
- | 2.0.2.RELEASE | 2018-05 | Fomchiey.BULD-SNAPSHOT | 2018-x |
- | 2.0.6.RELEASE | 2018-10 | Fomchiey-SR2 | 2018-10 |
- | 2.1.4.RELEASE | 2019-04 | Greenwich.SR1 | 2019-03 |
Use the last two
4.3 create parent project
- Create a new parent project springcloud. Remember that packaging is a pom mode
- It is mainly to define POM files and uniformly extract the jar packages shared by subsequent sub modules, which is similar to an abstract parent class
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.haust</groupId> <artifactId>springcloud</artifactId> <version>1.0-SNAPSHOT</version> <modules> <module>springcloud-api</module> <module>springcloud-provider-dept-8001</module> <module>springcloud-consumer-dept-80</module> <module>springcloud-eureka-7001</module> <module>springcloud-eureka-7002</module> <module>springcloud-eureka-7003</module> <module>springcloud-provider-dept-8002</module> <module>springcloud-provider-dept-8003</module> <module>springcloud-consumer-dept-feign</module> <module>springcloud-provider-dept-hystrix-8001</module> <module>springcloud-consumer-hystrix-dashboard</module> <module>springcloud-zuul-9527</module> <module>springcloud-config-server-3344</module> <module>springcloud-config-client-3355</module> <module>springcloud-config-eureka-7001</module> <module>springcloud-config-dept-8001</module> </modules> <!--Packaging method pom--> <packaging>pom</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <junit.version>4.12</junit.version> <log4j.version>1.2.17</log4j.version> <lombok.version>1.16.18</lombok.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>0.2.0.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <!--springCloud Dependence of--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Greenwich.SR1</version> <type>pom</type> <scope>import</scope> </dependency> <!--SpringBoot--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.1.4.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <!--database--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <!--SpringBoot starter--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!--Log test~--> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </dependency> </dependencies> </dependencyManagement> </project>
The parent project is springcloud, under which there are multiple child Mudules. Please refer to the complete code for details
springcloud-consumer-dept-80 access the controller under springcloud-provider-dept-8001 and use REST mode
Such as deptconsumercontroller java
/** * @Auther: csp1999 * @Date: 2020/05/17/22:44 * @Description: */ @RestController public class DeptConsumerController { /** * Understanding: consumers should not have a service layer~ * RestTemplate .... For us to call directly! Register in Spring * (Address: url, entity: map, class < T > responsetype) * <p> * Provide a variety of convenient methods to access remote http services and a simple Restful service template~ */ @Autowired private RestTemplate restTemplate; /** * Service provider address prefix * <p> * 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"; /** * Add department information to the consumer * @param dept * @return */ @RequestMapping("/consumer/dept/add") public boolean add(Dept dept) { // Postforobject (service provider address (Interface), parameter entity, return type class) return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept, Boolean.class); } /** * The consumer queries the Department information according to the id * @param id * @return */ @RequestMapping("/consumer/dept/get/{id}") public Dept get(@PathVariable("id") Long id) { // Service provider type (for object), return address (for object) class) return restTemplate.getForObject(REST_URL_PREFIX + "/dept/get/" + id, Dept.class); } /** * Consumer query department information list * @return */ @RequestMapping("/consumer/dept/list") public List<Dept> list() { return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class); } }
Before using resttemplet, you need to put it into the Spring container
ConfigBean.java
@Configuration public class ConfigBean { //@Configuration -- spring applicationContext.xml //Configure load balancing to implement RestTemplate // IRule // Roundrobin rule polling // RandomRule random // Availability filtering rule: it will filter out, trip, access the failed service ~, and poll the rest~ // RetryRule: the service will be obtained according to the polling ~, and if the service acquisition fails, it will be carried out within the specified time and try again @Bean public RestTemplate getRestTemplate(){ return new RestTemplate(); } }
The dao interface of springcloud-provider-dept-8001 calls pojo under the springcloud API module. You can use the pom file in springcloud-provider-dept-8001 to import the methods that the springcloud API module depends on:
<!--We need to get the entity class, so we need to configure it api module--> <dependency> <groupId>com.haust</groupId> <artifactId>springcloud-api</artifactId> <version>1.0-SNAPSHOT</version> </dependency>
POM of springcloud-consumer-dept-80 and springcloud-provider-dept-8001 XML is basically the same as the dependency under the parent project. You can directly look at the complete code without adding duplicate notes.
5. Eureka service registry
5.1 what is Eureka
- Netflix follows the API principle 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 configuration file of service invocation, The function is similar to Dubbo's registry, such as Zookeeper
5.2 principle understanding
-
Eureka basic architecture
- Spring cloud encapsulates the Eureka module developed by Netflix to realize service registration and discovery (compared with Zookeeper)
- Eureka adopts 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 the normal operation of each micro service in the system through EurekaServer. Some other modules of spring cloud (such as Zuul) can find other micro services in the system through EurekaServer and execute relevant logic
-
Compare with Dubbo architecture
- 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 information of all class service nodes will be stored in the service registry in Eureka Server, 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
- Eureka Server: provides service registration and discovery
- Service Provider: the service producer registers its own services in Eureka so that the service consumer can find them
- Service Consumer: the Service Consumer. Get the list of registered services from Eureka to find the consumer services
- Current project status
5.3 construction steps
1. eureka-server
- Establishment of springcloud-eureka-7001 module
-
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>
-
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 Registration Center (this module itself is a server, so it is not required) register-with-eureka: false # If 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/
The default port and access path of Eureka in the source code:
-
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); } }
- Access after successful startup http://localhost:7001/ Get the following page
2. eureka-client
Adjust the previously created springlouc-provider-dept-8001
-
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>
-
Eureca configuration added in application
# Eureka configuration: configure the service registry address eureka: client: service-url: defaultZone: http://localhost:7001/eureka/
-
Add to main startup class @EnableEurekaClient annotation
/** * @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); } }
- First start the 7001 server, then start the 8001 client for testing, and then access the monitoring page http://localhost:7001/ The production results are shown in the figure. It is successful
-
Modify the default description information on Eureka
# Eureka configuration: configure the service registry address eureka: client: service-url: defaultZone: http://localhost:7001/eureka/ instance: instance-id: springcloud-provider-dept-8001 #Modify the default description information on Eureka
The results are shown in the figure below:
If you stop springcloud-provider-dept-8001 at this time, the monitoring will turn on the protection mechanism after 30s:
- Configure monitoring information about service loading
pom. Adding dependencies to XML
<!--actuator Improve monitoring information--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
application. Add configuration in YML
# info configuration info: # Name of the project app.name: haust-springcloud # Company name company.name: Hunan software vocational and Technical University
Refresh the monitoring page and click to enterJump to a new page and display the following contents:
3. EureKa 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, when eureka server does not receive the heartbeat of an instance within a certain period of time, it will delete the instance from the registry (the default is 90 seconds). However, if a large number of instance heartbeats are lost in a short period of time, 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 the development process). When the number of heartbeats received in one minute decreases significantly, the protection mechanism will be triggered. You can see Renews threshold and Renews(last min) in the eureka management interface. When the latter (heartbeat received in the last minute) is less than the former (heartbeat threshold), the protection mechanism will be triggered and a red warning will appear: EMERGENCY!EUREKA MAY BE INCORRECTLY CLAIMING INSTANCES ARE UP WHEN THEY'RE NOT.RENEWALS ARE LESSER THAN THRESHOLD AND HENCE THE INSTANCES ARE NOT BEGING EXPIRED JUST TO BE SAFE. As can be seen from the warning, eureka believes that although it cannot receive the heartbeat of instances, it believes that instances are still healthy. eureka will protect these instances and will not delete them from the registry.
- The purpose of this protection mechanism is to avoid network connection failure. In case of network failure, the micro service and the registration center cannot communicate normally, but the service itself is healthy and should not be cancelled. If eureka mistakenly deletes the micro service due to network failure, the micro service will not be re registered with eureka server even if the network is restored, Because the registration request will be initiated only when the micro service is started, and then only the heartbeat and service list request will be sent. In this way, although the instance is running, it will never be perceived by other services. Therefore, when eureka server loses too many client heartbeats in a short time, it will enter the self-protection mode. In this mode, eureka will protect the information in the registry and will not log off any microservices. When the network fault recovers, eureka will automatically exit the protection mode. The self-protection mode can make the cluster more robust.
- However, in the development and testing phase, we need to restart publishing frequently. If the protection mechanism is triggered, the old service instance is not deleted. At this time, the request may run to the old instance, and the instance has been closed, which will lead to request errors and affect the development and testing. Therefore, in the development and testing stage, we can turn off the self-protection mode. Just add the following configuration to the eureka server configuration file: eureka server. Enable self preservation = false [it is not recommended to turn off the self-protection mechanism]
For details, please refer to the following blog: eureka self-protection mechanism_ Column of wudiyong22 - CSDN blog_ eureka self-protection mechanism
Get some messages that the development team will use (4. Sign up)
DeptController.java new method
/** * DiscoveryClient It can be used to obtain some configuration information and get specific micro services! */ @Autowired private DiscoveryClient client; /** * Get some information about registered microservices ~, * * @return */ @GetMapping("/dept/discovery") public Object discovery() { // Get the list of micro services List<String> services = client.getServices(); System.out.println("discovery=>services:" + services); // Get a specific microservice information through the specific microservice id, applicaioinName; List<ServiceInstance> instances = client.getInstances("SPRINGCLOUD-PROVIDER-DEPT"); for (ServiceInstance instance : instances) { System.out.println( instance.getHost() + "\t" + // Host name instance.getPort() + "\t" + // Port number instance.getUri() + "\t" + // uri instance.getServiceId() // Service id ); } return this.client; }
Add in the main startup class @EnableDiscoveryClient Annotation
@SpringBootApplication // @Enable Eureka client enables Eureka client annotation and automatically registers the service with the registry after the service is started @EnableEurekaClient // @EnableEurekaClient opens the annotation of the service discovery client, which can be used to obtain some configuration information and obtain specific micro services @EnableDiscoveryClient public class DeptProvider_8001 { ... }
The results are shown in the figure below:
5.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)
<!--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>
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 Registration Center (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~ # Rewrite 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 local names, find the local hosts file and open it
Add the name of the local machine to be accessed at the end of the hosts file. The default is localhost
Modify application The configuration of YML, as shown in the figure, is springcloud-eureka-7001 configuration, and springcloud-eureka-7002/springcloud-eureka-7003 can also be modified to their corresponding names
Associate springcloud-eureka-7001 with springcloud-eureka-7002 and springcloud-eureka-7003 in the cluster
Complete application under springcloud-eureka-7001 YML is as follows
server: port: 7001 #Eureka configuration eureka: instance: hostname: eureka7001.com #Instance name of Eureka server client: register-with-eureka: false #Indicates whether to register yourself with Eureka Registration Center (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~ #Rewrite Eureka's default port and access path -- > http://localhost:7001/eureka/ # Stand alone: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ # Cluster (Association): 7001, 7002, 7003 defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
At the same time, associate springcloud-eureka-7002 with springcloud-eureka-7001 and springcloud-eureka-7003 in the cluster
Complete application under springcloud-eureka-7002 YML is as follows
server: port: 7002 #Eureka configuration eureka: instance: hostname: eureka7002.com #Instance name of Eureka server client: register-with-eureka: false #Indicates whether to register yourself with Eureka Registration Center (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~ #Rewrite Eureka's default port and access path -- > http://localhost:7001/eureka/ # Stand alone: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ # Cluster (Association): 7002, 7001, 7003 defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7003.com:7003/eureka/
Spring cloud-eureka-7003 can be configured in the same way
Modify Eureka configuration through the yml configuration file under springcloud-provider-dept-8001: configure the service registry address
# Eureka configuration: configure the service registry address eureka: client: service-url: # Registration center address 7001-7003 defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ instance: instance-id: springcloud-provider-dept-8001 #Modify the default description information on Eureka
In this way, the simulation cluster is set up, and a project can be attached to three servers
5.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
4. 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, and may generally have lower requirements for consistency
5. As a distributed service registry, where is Eureka better than Zookeeper?
The famous CAP theory points out that A distributed system cannot meet C (consistency), A (availability) and P (fault tolerance) at the same time. Because partition fault tolerance P must be guaranteed in the distributed system, we can only trade off between A and C.
- Zookeeper ensures that CP - > systems that meet consistency and partition fault tolerance usually have low performance
- Eureka guarantees that AP - > systems that meet availability and partition fault tolerance may generally have lower requirements for consistency
Zookeeper guarantees CP
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, there will be such a situation in zookeeper. When the master node loses contact with other nodes due to network failure, the remaining nodes will conduct leader election again. The problem is that the election leader takes too long, 30-120s, and the whole zookeeper cluster is unavailable during the election, which leads to the paralysis of the registration service during the election. In the cloud deployment environment, the loss of the master node of the zookeeper cluster due to network problems is an event with a high probability. Although the service can be restored eventually, the long election time leads to the long-term unavailability of registration, which is intolerable.
Eureka guarantees AP
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 Eureka's client registers with an Eureka, if it finds that 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. In addition, Eureka also has a self-protection mechanism. If more than 85% of the nodes do not have a normal heartbeat within 15 minutes, Eureka thinks that there is a network failure between the client and the registry. At this time, the following situations will occur:
- Eureka is no longer removing services that should expire because they haven't received a heartbeat for a long time from the registration list
- Eureka can still accept the registration and query requests of new services, but it will not be synchronized to other nodes (that is, ensure that the current node is still available)
- When the network is stable, the new registration information of the current instance will be synchronized to other nodes
Therefore, Eureka can deal with the loss of contact of some nodes due to network failure without paralyzing the whole registration service like zookeeper
6. Ribbon: load balancing (client based)
6.1 load balancing and Ribbon
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. Provide a complete set of components such as timeout and retry of client connection. 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 custom load balancing algorithm!
What can Ribbon do?
- LB, load balancer, is an application often used in microservices or distributed clusters.
- Load balancing simply means that users' requests are evenly distributed to multiple services, so as to achieve the HA (high use) of the system.
- Common load balancing software include Nginx, Lvs and so on.
- Both Dubbo and spring cloud provide us with load balancing. The load balancing algorithm of spring cloud can be customized.
-
Simple classification of load balancing:
-
Centralized LB
- That is, an independent LB facility is used between the service provider and the consumer, such as nginx (reverse proxy server), which is responsible for forwarding the access request to the service provider through some policy!
-
Program LB
- Integrate LB logic into the consumer. The consumer knows which addresses are available from the service registry, and then selects a suitable server from these addresses.
- Ribbon belongs to in-process LB, which is just a class library integrated into the consumer process. The consumer obtains the address of the service provider through it!
-
6.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 YML file
# Eureka configuration eureka: client: register-with-eureka: false # Do not register yourself with Eureka service-url: # Visit one of the three registries at random defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
Main startup class plus @EnableEurekaClient Annotation, open Eureka
//After the integration of Ribbon and Eureka, the client can call directly without caring about the IP address and port number @SpringBootApplication @EnableEurekaClient //Open Eureka client 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 public class ConfigBean { //@Configuration -- spring applicationContext.xml @LoadBalanced //Configure load balancing to implement RestTemplate @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } }
Modify the controller: deptconsumercontroller java
//Ribbon: the address here should be a variable, accessed through the service name //private static final String REST_URL_PREFIX = "http://localhost:8001"; private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";
6.3 load balancing using Ribbon
flow chart:
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 in turn 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
Visit again http://localhost/consumer/dept/list At this time, the random service provider 8001
Each visit above http://localhost/consumer/dept/list Random access to a service provider in the cluster is called polling , the polling algorithm can be customized in spring cloud.
How to switch or customize rules?
Configure in the ConfigBean under the springcloud-provider-dept-80 module and switch to different rules
@Configuration public class ConfigBean { //@Configuration -- spring applicationContext.xml /** * 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 carried out within the specified time and try again */ @Bean public IRule myRule() { return new RandomRule();//Use random strategy //return new RoundRobinRule();// Use polling policy //return new AvailabilityFilteringRule();// Use polling policy //return new RetryRule();// Use polling policy } }
You can also customize rules and customize a configuration class myRule under myRule package Java, note: this package should not be at the same level as the package where the main startup class is located, but at the same level as the package where the startup class is located:
MyRule.java
/** * @Auther: csp1999 * @Date: 2020/05/19/11:58 * @Description: Custom rules */ @Configuration public class MyRule { @Bean public IRule myRule(){ return new MyRandomRule();//The default is to poll RandomRule, which is now customized as its own } }
The main startup class enables load balancing and specifies a custom MyRule configuration class
//After the integration of Ribbon and Eureka, the client can call directly without caring about the IP address and port number @SpringBootApplication @EnableEurekaClient //The customized Ribbon class can be loaded when the micro service is started (the customized rules will override the original default rules) @RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT",configuration = MyRule.class)//Turn on load balancing and specify custom rules public class DeptConsumer_80 { public static void main(String[] args) { SpringApplication.run(DeptConsumer_80.class, args); } }
Custom rules (here we refer to the default rule code in the Ribbon and change it slightly): myrandomrule java
public class MyRandomRule extends AbstractLoadBalancerRule { /** * If each service is accessed 5 times, the next service will be replaced (a total of 3 services) * <p> * total=0,Default = 0. If = 5, it points to the next service node * index=0,Default = 0, if total=5,index+1 */ private int total = 0;//Number of calls private int currentIndex = 0;//Who is currently providing services //@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE") public Server choose(ILoadBalancer lb, Object key) { if (lb == null) { return null; } Server server = null; while (server == null) { if (Thread.interrupted()) { return null; } List<Server> upList = lb.getReachableServers();//Access to currently alive services List<Server> allList = lb.getAllServers();//Get all services int serverCount = allList.size(); if (serverCount == 0) { /* * No servers. End regardless of pass, because subsequent passes * only get more restrictive. */ return null; } //int index = chooseRandomInt(serverCount);// Generating interval random number //server = upList.get(index);// Randomly get one from a or living service //=====================Custom code========================= if (total < 5) { server = upList.get(currentIndex); total++; } else { total = 0; currentIndex++; if (currentIndex > upList.size()) { currentIndex = 0; } server = upList.get(currentIndex);//Obtain the specified service from the living service for operation } //====================================================== if (server == null) { /* * The only time this should happen is if the server list were * somehow trimmed. This is a transient condition. Retry after * yielding. */ Thread.yield(); continue; } if (server.isAlive()) { return (server); } // Shouldn't actually happen.. but must be transient or a bug. server = null; Thread.yield(); } return server; } protected int chooseRandomInt(int serverCount) { return ThreadLocalRandom.current().nextInt(serverCount); } @Override public Server choose(Object key) { return choose(getLoadBalancer(), key); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { // TODO Auto-generated method stub } }
7.Feign: load balancing (based on the server)
7.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
- Microservice name [ribbon]
- Interface and notes [feign]
What can Feign do?
- Feign aims to make it easier to write Java Http clients
- Previously, when using Ribbon + RestTemplate, the RestTemplate is used to encapsulate the Http request, forming a set of templated calling methods. However, in the actual development, because there may be more than one invocation of service dependencies, and often an interface will be invoked in multiple places, a client class is usually encapsulated for each micro service to wrap the invocation of these dependent services. Therefore, Feign has made further encapsulation on this basis and helped us define and implement the definition of dependent service interface. 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, now it is a micro service interface with a Feign Annotation on it), The interface binding to the service provider can be completed, which simplifies the development of automatically encapsulating the service call client when using the Spring Cloud Ribbon.
Feign integrates Ribbon by default
- The Ribbon is used to maintain the service list information of microservicecloud dept, and the load balancing of the client is realized through polling. Different from the Ribbon, Feign only needs to define the service binding interface and realize the service invocation in a declarative way.
7.2 use steps of feign
-
Create the springcloud consumer fdept feign module
Copy the POM under the springcloud-consumer-dept-80 module XML, resource, and java code to the springcloud consumer feign module, and add feign dependencies.
<!--Feign Dependence of--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> <version>1.4.6.RELEASE</version> </dependency>
Realized through the Ribbon: - the original controller: deptconsumercontroller java
``````````
/**- @Auther: csp1999
- @Date: 2020/05/17/22:44
- @Description:
*/
@RestController
public class DeptConsumerController {
/** * Understanding: consumers should not have a service layer~ * RestTemplate .... For us to call directly! Register in Spring * (Address: url, entity: map, class < T > responsetype) * <p> * Provide a variety of convenient methods to access remote http services and a simple Restful service template~ */ @Autowired private RestTemplate restTemplate; /** * Service provider address prefix * <p> * 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"; /** * Add department information to the consumer * @param dept * @return */ @RequestMapping("/consumer/dept/add") public boolean add(Dept dept) { // Postforobject (service provider address (Interface), parameter entity, return type class) return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept, Boolean.class); } /** * The consumer queries the Department information according to the id * @param id * @return */ @RequestMapping("/consumer/dept/get/{id}") public Dept get(@PathVariable("id") Long id) { // Service provider type (for object), return address (for object) class) return restTemplate.getForObject(REST_URL_PREFIX + "/dept/get/" + id, Dept.class); } /** * Consumer query department information list * @return */ @RequestMapping("/consumer/dept/list") public List<Dept> list() { return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class); } } `````````` adopt**Feign**Realization: - after transformation controller: **DeptConsumerController.java** `````````` /** * @Auther: csp1999 * @Date: 2020/05/17/22:44 * @Description: */ @RestController public class DeptConsumerController { @Autowired private DeptClientService deptClientService; /** * Add department information to the consumer * @param dept * @return */ @RequestMapping("/consumer/dept/add") public boolean add(Dept dept) { return deptClientService.addDept(dept); } /** * The consumer queries the Department information according to the id * @param id * @return */ @RequestMapping("/consumer/dept/get/{id}") public Dept get(@PathVariable("id") Long id) { return deptClientService.queryById(id); } /** * Consumer query department information list * @return */ @RequestMapping("/consumer/dept/list") public List<Dept> list() { return deptClientService.queryAll(); } } `````````` Feign and Ribbon Compared with the two, the former shows the characteristics of interface oriented programming, the code looks more refreshing, and Feign The calling method is more in line with what we were doing before SSM perhaps SprngBoot During the project, Controller Layer call Service Layer programming habits! **Main configuration class**: `````````` /** * @Auther: csp1999 * @Date: 2020/05/17/22:47 * @Description: */ @SpringBootApplication @EnableEurekaClient // feign client annotation, and specify the package to be scanned and the configuration interface DeptClientService @EnableFeignClients(basePackages = { "com.haust.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); } } ``````````
-
Transforming the spring cloud API module
pom. Adding feign dependency to XML
<!--Feign Dependence of--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> <version>1.4.6.RELEASE</version> </dependency>
Create a new service package and a new deptclientservice Java interface,
``````````
// @FeignClient : microservice client annotation, value: specify the name of the microservice, so that Feign client can directly find the corresponding microservice
@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); } ``````````
7.3 how to choose feign and Ribbon?
It depends on personal habits. If you like REST style, use Ribbon; If you like the community version of the interface oriented style, use Feign
Feign essentially implements Ribbon, but the latter is in the calling mode, in order to meet the interface calling habits of some developers!
Now let's close the service consumer of springcloud-consumer-dept-80 and replace it with springcloud-consumer-dept-feign (port is still 80): (it can still be accessed normally, that is, the calling method is changed compared with the Ribbon)
8. Hystrix: Service fuse
Problems faced by distributed systems
Applications in complex distributed architecture have dozens of dependencies, and each dependency will inevitably fail at some time!
8.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".
For high traffic applications, a single back-end dependency may cause all resources on all servers to saturate in tens of seconds. Worse than failure, 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. All these indicate the need to isolate and manage failures and delays to achieve the failure of a single dependency without affecting the operation of the whole application or system.
Give up the car, we need to give up the car!
8.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 in the case of a dependency failure, it will not lead to the service failure of the whole system, 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.
8.3 what can hystrix do?
- service degradation
- Service fuse
- Service current limiting
- Near real-time monitoring
- ...
When everything is normal, 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:
With the increase of high-capacity traffic, the potential of a single back-end dependency will cause all resources on all servers to saturate in a few seconds.
Every point in the application that may cause network requests through the network or client library is the source of potential failures. Worse than failure, these applications can also lead to increased latency between services, backing up queues, threads, and other system resources, resulting in more cascading failures across systems.
When you wrap each base dependency with Hystrix, the architecture shown in the above diagram changes similar to the following diagram. Each dependency is isolated from each other, limited to the resources it can fill when the delay occurs, and included in the fallback logic, which determines the response to any type of failure in the dependency:
Official website information: https://github.com/Netflix/Hystrix/wiki
8.4 service fuse
What is service?
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. In the spring cloud framework, the fuse mechanism is implemented through hystrix. Hystrix will monitor the status of calls between microservices. When the failed call reaches a certain threshold, the default is 20 calls in 5 seconds, and the circuit breaker mechanism will be started. The notes of the circuit breaker mechanism are: @HystrixCommand.
The service can solve the following problems:
- When the dependent object is unstable, it can achieve the purpose of rapid failure;
- After a fast failure, it can dynamically test whether the dependent object is restored according to a certain algorithm.
Introductory case
Create a new springcloud provider Dept hystrix-8001 module and copy the POM in springcloud provider Dept – 8001 XML, resource, and Java code to initialize and adjust.
Import hystrix dependency
<!--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: # pojo package under spring cloud API module type-aliases-package: com.haust.springcloud.pojo # Mybatis config. Under this module XML core configuration file classpath config-location: classpath:mybatis/mybatis-config.xml # mapper configuration file classpath under this module mapper-locations: classpath:mybatis/mapper/*.xml # spring configuration spring: application: #Project name name: springcloud-provider-dept datasource: # Druid data source type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/db01?useUnicode=true&characterEncoding=utf-8 username: root password: root # Eureka configuration: configure the service registry address eureka: client: service-url: # Registration center address 7001-7003 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 prefer-ip-address: true #After changing to true, the default display is the ip address instead of localhost #info configuration info: app.name: haust-springcloud #Name of the project company.name: com.haust #Company name
prefer-ip-address: false:
prefer-ip-address: true:
Modify controller
/** * @Auther: csp1999 * @Date: 2020/05/17/22:06 * @Description: Provide Restful services */ @RestController public class DeptController { @Autowired private DeptService deptService; /** * Query department information according to id * If there is an exception in the query based on id, follow the alternative code of hystrixGet * @param id * @return */ @HystrixCommand(fallbackMethod = "hystrixGet") @RequestMapping("/dept/get/{id}")//Query by id public Dept get(@PathVariable("id") Long id){ Dept dept = deptService.queryById(id); if (dept==null){ throw new RuntimeException("this id=>"+id+",The user does not exist or the information cannot be found~"); } return dept; } /** * Query alternatives according to id (fuse) * @param id * @return */ public Dept hystrixGet(@PathVariable("id") Long id){ return new Dept().setDeptno(id) .setDname("this id=>"+id+",No corresponding information,null---@Hystrix~") .setDb_source("stay MySQL This database does not exist in"); } }
Add supporting annotations for the main startup class @EnableCircuitBreaker
/** * @Auther: csp1999 * @Date: 2020/05/17/22:09 * @Description: Startup class */ @SpringBootApplication @EnableEurekaClient // The startup class of EnableEurekaClient client automatically registers the service with the registry after the service is started @EnableDiscoveryClient // Service discovery~ @EnableCircuitBreaker // Add supporting comments for fuse public class HystrixDeptProvider_8001 { public static void main(String[] args) { SpringApplication.run(HystrixDeptProvider_8001.class,args); } }
Test:
After using fuse, when accessing a nonexistent id, the data displayed on the foreground page is as follows:
If the springcloud provider Dept – 8001 module that is not applicable accesses the same address, the following conditions will occur:
Therefore, it is necessary to use fuse in order to avoid errors in the whole application or web page due to exceptions or errors in the background of a micro service
8.5 service degradation
What is service degradation?
Service degradation means that when the pressure on the server increases sharply, some services and pages are not handled strategically or handled in a simple way according to the actual business conditions and traffic, so as to release the server resources to ensure the normal or efficient operation of the core business. To put it bluntly, it is to give system resources to services with high priority as much as possible.
Resources are limited and requests are unlimited. If the service is not degraded during the peak period of concurrency, on the one hand, it will certainly affect the performance of the overall service. If it is serious, it may lead to downtime and unavailability of some important services. Therefore, in the peak period, in order to ensure the availability of core function services, some services must be degraded. 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.
What are the main scenarios for service degradation? When the overall load of the whole microservice architecture exceeds the preset upper threshold or the upcoming traffic is expected to exceed the preset threshold, some unimportant or non urgent services or tasks can be delayed or suspended in order to ensure the normal operation of important or basic services.
For example, you can add points to the service cache according to the method of service execution delay; Or close the service within the granularity, such as the recommendation of relevant articles.
It can be seen from the above figure that when the traffic of service A increases sharply and the traffic of B and C is less at A certain time, in order to alleviate the pressure of service A, B and C need to temporarily close some service functions to undertake some services of A, so as to share the pressure for A, which is called service degradation.
Issues to be considered in service degradation
- 1) Which services are core services and which are non core services
- 2) Which services can support degradation, which services cannot support degradation, what is the degradation strategy
- 3) In addition to service degradation, is there a more complex business release scenario and what is the strategy?
Automatic degradation classification
1) Timeout degradation: it mainly configures the timeout time and timeout retry times and mechanism, and uses asynchronous mechanism to detect the reply
2) Degradation of failure times: it mainly refers to some unstable APIs. When the number of failed calls reaches a certain threshold, it will be degraded automatically. Similarly, asynchronous mechanism should be used to detect the reply
3) Failure degradation: for example, if the remote service to be called hangs (network failure, DNS failure, http service returns an error status code, rpc service throws an exception), it can be directly degraded. The processing schemes after degradation include: default value (for example, if the inventory service is suspended, return to the default stock), bottom data (for example, if the advertisement is suspended, return some static pages prepared in advance), cache (some cache data temporarily stored before)
4) Current limit degradation: when second killing or rush buying some restricted goods, the system may crash due to too much traffic. At this time, the current limit will be used to limit the traffic. When the current limit threshold is reached, the subsequent requests will be degraded; The processing scheme after degradation can be: queue page (divert the user to the queue page and try again later), no goods (directly inform the user that there is no goods), error page (if the activity is too hot, try again later).
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 now") .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: # Visit 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
8.6 difference between service fusing and degradation
- Service fusing - > server: a service timeout or abnormality 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 the decline of 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) failure, 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)
- The implementation method is different. Service degradation is code intrusive (completed by the controller and / or automatic degradation), and fusing is generally called self fusing.
Fusing, degradation, current limiting:
Flow restriction: limit concurrent request access. If the threshold is exceeded, it will be rejected;
Core services are guaranteed to be unavailable (non stable), and core services are guaranteed to be degraded (priority); Considering the overall load;
Fusing: the dependent downstream service failure triggers fusing to avoid causing the system to crash; Automatic system execution and recovery
8.7 Dashboard flow monitoring
Create a new springcloud consumer hystrix dashboard module
Add 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-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()); //Visiting this page is the monitoring page registrationBean.addUrlMappings("/actuator/hystrix.stream"); return registrationBean; } }
visit: http://localhost:9001/hystrix
Enter the monitoring page:
The effect is as follows:
9. Zull routing gateway
summary
What is zuul?
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 processing process of requests, 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.
Note: Zuul service will eventually register with Eureka
It provides three functions: agent + routing + filtering!
What can Zuul do?
- route
- filter
Official documents: https://github.com/Netflix/zuul/
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 #Microservice name # eureka registry configuration eureka: client: service-url: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ instance: #id of the instance instance-id: zuul9527.com prefer-ip-address: true # Display ip info: app.name: haust.springcloud # entry name company.name: Xiyuan campus of Henan University of science and technology # corporate name # zull routing gateway configuration zuul: # Routing related configuration # Original access route eg:http://www.cspStudy.com:9527/springcloud-provider-dept/dept/get/1 # After zull route configuration, access the route eg:http://www.cspstudy.com:9527/haust/mydept/dept/get/1 routes: mydept.serviceId: springcloud-provider-dept # Service provider routing name of eureka registry mydept.path: /mydept/** # Change the service provider route name of eureka registry to a custom route name # You can no longer use this path to access, *: ignore and hide all service names~ ignored-services: "*" # Set public prefix prefix: /haust
Main startup class
/** * @Auther: csp1999 * @Date: 2020/05/20/20:53 * @Description: Zull Routing gateway main startup class */ @SpringBootApplication @EnableZuulProxy // Open Zuul public class ZuulApplication_9527 { public static void main(String[] args) { SpringApplication.run(ZuulApplication_9527.class,args); } }
Test:
It can be seen that Zull routing gateway has been registered in Eureka registry!
The above figure shows the route accessed by the service interface when it is not configured by the Zull routing gateway. It can be seen that it is not safe to access it directly with the name of the micro service (service provider). You can't expose the name of the micro service!
Therefore, after Zull routing gateway configuration, the access routes are:
We can see that the microservice name is replaced and hidden, replaced by our custom microservice name mydept, and prefixed with haust, so as to encrypt the access of routing fan!
For details, please refer to the springcloud Chinese community zuul component: https://www.springcloud.cc/spring-cloud-greenwich.html\#\_router\_and\_filter\_zuul
10. Spring Cloud Config distributed configuration
Dalston.RELEASE
Spring Cloud Config provides server and client support for external configurations in distributed systems. With Config Server, you can manage external properties of applications in all environments. The conceptual mappings on the client and server are the same as the spring Environment and PropertySource abstractions, so they fit well with spring applications, but can be used with any application running in any language. As applications go through the deployment process from developers to test and production, you can manage the configuration between these environments and determine that the application has everything you need to run when migrating. The default implementation of the server storage back-end uses git, so it easily supports the configuration Environment of label version and can access various tools for managing content. It's easy to add an alternative implementation and insert it using the spring configuration.
summary
Configuration file problems faced by distributed systems
Microservice means to split the business in a single application into a sub service. The granularity of each service is relatively small, so there will be a large number of services in the system. Because each service needs the necessary configuration information to run, a set of centralized and dynamic configuration management facilities is essential. spring cloud provides configServer to solve this problem. Each microservice brings an application YML, it's a headache to modify hundreds of configuration files!
What is the spring cloud config distributed configuration center?
spring cloud config provides centralized external support for microservices in the microservice architecture, and the configuration server provides a centralized external configuration for all links of different microservice applications.
spring cloud config is divided into two parts: server and client.
The server, also known as} distributed configuration center, is an independent micro service application, which is used to connect to the configuration server and provide access interfaces for the client to obtain configuration information, encrypt and decrypt 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.
What can the spring cloud config distributed configuration center do?
- Centralized management profile
- Different environments, different configurations, dynamic configuration updates, 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 change of the configuration and apply the new configuration
- Expose the configuration information in the form of REST interface
Integration of spring cloud config distributed configuration center and GitHub
Because spring cloud config uses git to store configuration files by default (there are other ways, such as self-contained SVN and local files), Git is the most recommended and is accessed in the form of http / https.
Introductory case
Server
Create a new springcloud-config-server-3344 module and import POM XML dependency
<dependencies> <!--web--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--config--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> <version>2.1.1.RELEASE</version> </dependency> <!--eureka--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> <version>1.4.6.RELEASE</version> </dependency> </dependencies>
Create application. Under resource YML configuration file, Spring Cloud Config server provides configuration for remote clients from git repository (required):
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 is incorrect # Or directly comment out the eureka dependency. eureka is temporarily unavailable here eureka: client: register-with-eureka: false fetch-registry: false
Main startup class
@EnableConfigServer // Start the spring cloud config server service @SpringBootApplication public class Config_server_3344 { public static void main(String[] args) { SpringApplication.run(Config_server_3344.class,args); } }
Put the newly created application.config in the springcloud config folder of the local git warehouse YML submitted to code cloud warehouse:
The default strategy for locating resources is to clone a git repository (in spring.cloud.config.server.git.uri) and use it to initialize a mini spring application. The Environment of the applet is used to enumerate property sources and publish them through JSON endpoints.
The HTTP service has resources in the following format:
/{ application}/{ profile}[/{ label}] /{ application}-{ profile}.yml /{ label}/{ application}-{ profile}.yml /{ application}-{ profile}.properties /{ label}/{ application}-{ profile}.properties
Where "application" is used as spring in spring application config. Name injection (usually "application" in conventional Spring Boot applications), "configuration file" is the active configuration file (or the attribute of comma separated list), and "label" is the optional git label (the default is "master").
Test access http://localhost:3344/application-dev.yml
Test access http://localhost:3344/application/test/master
Test access http://localhost:3344/master/application-dev.yml
If the test accesses a configuration that does not exist, it will not be displayed, such as: http://localhost:3344/master/application-aaa.yml
client
Put the newly created config client in the springcloud config folder of the local git warehouse YML submitted to code cloud warehouse:
Create a new springcloud-config-client-3355 module and import dependencies
<!--config--> <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-start --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> <version>2.1.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
Create application. Under resources YML and bootstrap YML profile
bootstrap.yml# is a system level configuration
# System level configuration spring: cloud: config: name: config-client # The resource name that needs to be read from git without suffix profile: dev label: master uri: http://localhost:3344
application.yml# is a user level configuration
# User level configuration spring: application: name: springcloud-config-client
Create the configclientcontroller under the controller package Java for testing
@RestController public class ConfigClientController { @Value("${spring.application.name}") private String applicationName; //Get microservice name @Value("${eureka.client.service-url.defaultZone}") private String eurekaServer; //Get Eureka services @Value("${server.port}") private String port; //Get the port number of the server @RequestMapping("/config") public String getConfig(){ return "applicationName:"+applicationName + "eurekaServer:"+eurekaServer + "port:"+port; } }
Main startup class
@SpringBootApplication public class ConfigClient { public static void main(String[] args) { SpringApplication.run(ConfigClient.class,args); } }
Test:
Start server Config_server_3344 restart the client ConfigClient
visit: http://localhost:8201/config/
Small case
Create config-dept.yml and config eureka.com locally YML and submit to code cloud warehouse
Here, the content of the configuration file is no longer listed, but directly to the code.
Create a new springcloud-config-eureka-7001 module and copy the contents under the original springcloud-eureka-7001 module to this module.
1. Clear the application of this module YML configuration and create a new bootstrap YML connection remote configuration
spring: cloud: config: name: config-eureka # Profile name in warehouse label: master profile: dev uri: http://localhost:3344
2. In POM Add spring cloud config dependency to XML
<!--config--> <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-config --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> <version>2.1.1.RELEASE</version> </dependency>
3. Main startup
@SpringBootApplication @EnableEurekaServer //The startup class of EnableEurekaServer server can accept others to register~ public class ConfigEurekaServer_7001 { public static void main(String[] args) { SpringApplication.run(ConfigEurekaServer_7001.class,args); } }
4. Test
Step 1: start Config_Server_3344, and visit http://localhost:3344/master/config-eureka-dev.yml Testing
Part II: start configurekaserver_ 7001, access http://localhost:7001/ Testing
If the above figure is displayed, it is successful
Create a new springcloud-config-dept-8001 module and copy the contents of springcloud-provider-dept-8001
Similarly, import spring cloud config dependency and empty application YML. Create a bootstrap YML configuration file and configure
spring: cloud: config: name: config-dept label: master profile: dev uri: http://localhost:3344
Main startup class
@SpringBootApplication @EnableEurekaClient //Automatically register in Eureka after the service starts! @EnableDiscoveryClient //Service discovery~ @EnableCircuitBreaker // public class ConfigDeptProvider_8001 { public static void main(String[] args) { SpringApplication.run(ConfigDeptProvider_8001.class,args); } //Add a Servlet @Bean public ServletRegistrationBean hystrixMetricsStreamServlet(){ ServletRegistrationBean registrationBean = new ServletRegistrationBean(new HystrixMetricsStreamServlet()); registrationBean.addUrlMappings("/actuator/hystrix.stream"); return registrationBean; } }