Stage 5: microservice system development: Spring Cloud getting started operation manual (day01)

Stage 5: distributed system development: microservice system development (day01) http://doc.canglaoshi.org/ Article ca...
Section 1: introduction to the concept of spring cloud
Section 2: composition of spring cloud framework technology
Section 3: Spring Cloud vs Dubbo
Layer 1: service core business - Analysis and build overview
Layer 2: service core business commons general project
Layer 3: item service
Section 1: working principle analysis
Section 2: implementation of item service high availability
Section 3: implementation of eureka high availability
Section one: the concept of ribbon
Section 2: how ribbon works
Section 3: RestTemplate execution remote call case
Section 4: RestTemplate class details
Section I: ribbon load balancing schematic diagram
Section 2: explanation of ribbon load balancing function cases
Section 3: explanation of ribbon retry function cases
Key issues:

Stage 5: distributed system development: microservice system development (day01)
http://doc.canglaoshi.org/

Article catalog

Chapter 1: Spring Cloud development environment

Section 1: STS tool installation
Section 2: Maven tool installation
Section 3: Lombok tool installation

Chapter 2: introduction to spring cloud framework

Section 1: introduction to the concept of spring cloud

spring cloud is a collection of frameworks. It makes use of the development convenience of spring boot to ingeniously simplify the development of distributed system infrastructure, such as service discovery registration, configuration center, message bus, load balancing, circuit breaker, data monitoring, etc., all of which can be started and deployed with one click using the development style of spring boot. spring cloud doesn't make wheels repeatedly. It just combines the mature and practical service frameworks developed by various companies, encapsulates and shields the complex configuration and implementation principles through spring boot style, and finally leaves a set of simple and easy to understand, deploy and maintain distributed system development kit for developers.

Spring cloud is a good news for small and medium-sized Internet companies, because these companies often do not have the strength or enough capital to develop their own distributed system infrastructure. Using spring cloud one-stop solution can calmly cope with business development while greatly reducing development costs. At the same time, with the popularity of microservice architecture and docker container concept in recent years, spring cloud will also have a place in the future of more and more "cloud" software development style neutrality, especially in the current diversified distributed solutions that provide standardized, one-stop technical solutions, which may be comparable to that of servlet s The birth of the standard effectively promotes the progress of the technical level of the server software system.

Section 2: composition of spring cloud framework technology


eureka
Microservice governance, service registration and discovery

ribbon
Load balancing, request retry

hystrix
Circuit breaker, service degradation, fusing

feign
ribbon + hystrix integration and declarative client

hystrix dashboard and turbo
hystrix data monitoring

zuul
API gateway, providing unified access to microservices, and providing unified permission verification

config
Configuration center

bus
Message bus, configuration refresh

sleuth+zipkin
Link tracking

Section 3: Spring Cloud vs Dubbo


Dubbo framework
Dubbo is just a remote call (RPC) framework
The default is based on long connection and supports multiple serialization formats

Spring Cloud framework
The Spring Cloud framework is a collection of frameworks.
Provides a complete set of micro service solutions (family bucket)
http based call, Rest API

Chapter 3: spring cloud case explanation

Layer 1: service core business - Analysis and build overview

1. The architecture of the core business of the integrated service is as follows: design and development document description

2. Now we use spring cloud for microservice development. The business requirement is that we have three modules in our project. Distributed is a parent-child relationship, while microservice is a composite relationship and a sibling relationship. It is a combination of many modules.
The temporary port numbers of the three service modules we set are as follows. Then we will start the practice in the specific i project.
1. item service, port 8001
2. user service, port 8101
3. order service, port 8201

3. Business service table diagram:

In our core business services in the figure above, we have three core business modules: commodity service module, user service module and order service module. So we need three tables. The three system modules cooperate and coordinate with each other.
First: in the commodity service module, we need to process the business that we need to obtain the commodity list of the order according to the order Id. Reduce inventory of goods.
Second: user service module, the business we need to deal with is that we need to increase user points according to user ID.
Third: order service module, the business we need to deal with is that we need to obtain order information and save order information.

Layer 2: service core business commons general project

Step 1: create a new maven project

Step 2: pom file import dependency

<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>cn.tedu</groupId> <artifactId>sp01-commons</artifactId> <version>0.0.1-SNAPSHOT</version> <name>sp01-commons</name> <dependencies> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-parameter-names</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jdk8</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-guava</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.6</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.26</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>

Step 3: java source file structure chart

Step 4: encapsulate the pojo entity class table

Because our business needs pojo entity table to encapsulate the data written to the database, and we extract this class into the common module system, which can reduce the code writing and improve the reuse rate of common code.

1 / package Item table (Item type data information), the specific code is as follows:

package cn.tedu.sp01.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class Item { private Integer id; private String name; private Integer number; }

2 / encapsulate the User table (User class data information). The specific code is as follows:

package cn.tedu.sp01.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class User { private Integer id; private String username; private String password; }

3. Encapsulate the order table (Order class data information). The specific code is as follows:

package cn.tedu.sp01.pojo; import java.util.List; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class Order { private String id; private User user; private List<Item> items; }

Step 5: encapsulate the service interface class of each module

Because we need low coupling and high cohesion in the project. And spring The characteristic of cloud microservice is that when the modules are separated, the system in a project is divided into many subsystems. Then, in the subsystem, each subsystem is divided into many and different modules, which are deployed on different servers. In this way, the high concurrency of the program can be improved, and the development function of the distributed system can be expanded. It is our system function, coupling degree, Compression resistance has been greatly improved, so our distribution is a million level, and our microservice is a billion level access system.

In order to realize the above functions, we display the interface coupled to the service business interface layer of our three different modules. The specific code design is as follows:

Layer 3: item service

General overview:
1. New project
2. Configuration dependency pom.xml
3. Configuration application.yml
4. Configure the main program
5. Write code

Step 1: start a new spring boot project

Chapter 4: building eureka server Chapter 9: high availability of eureka and "service providers"

Section 1: working principle analysis

Section 2: implementation of item service high availability

Section 3: implementation of eureka high availability

Chapter 10: ribbon service consumer (client load balancing tool)

Section one: the concept of ribbon

1. Introduction to the concept of ribbon
Spring Cloud Ribbon is a client-side load balancing tool based on HTTP and TCP, which is implemented based on netflixribon. Through the encapsulation of Spring Cloud, we can easily convert the service-oriented REST template request to the client-side load balanced service call automatically. Although Spring Cloud Ribbon is just a tool framework, it does not need to be deployed independently like service registry, configuration center and API gateway, but it exists in almost every microservice and infrastructure built by Spring Cloud. Because the call between microservices and the request forwarding of API gateway are actually implemented through the Ribbon, including Feign, which we will introduce later. It is also a Ribbon based implementation tool. Therefore, the understanding and use of Spring Cloud Ribbon is very important for us to use Spring Cloud to build microservices.
In this chapter, we will specifically introduce how to use Ribbon to achieve client load balancing, and through source code analysis to understand the basic principle of Ribbon to achieve client load balancing.

2. What is the client load balancing tool
Load balancing is a very important content in the system architecture, and it has to be implemented. Because load balancing is one of the most important means for high availability, network pressure relief and capacity expansion of the system. The load balancing of the system is divided into two types: server load balancing and client load balancing.

Server load balancing: we usually refer to server load balancing, which is divided into hardware load balancing and software load balancing. Hardware load balancing is mainly through the installation of devices dedicated to load balancing between server nodes, such as F5, etc.; while software load balancing is through the installation of server software with load balancing functions or modules to complete the request distribution work, such as Nginx, etc. No matter whether hardware load balancing or software load balancing is used, as long as the server load balancing can be built in the architecture similar to the following figure:

The hardware load balancing equipment or software load balancing software module will maintain a list of available servers, and remove the failed server nodes through heartbeat detection to ensure that all the servers in the list can be accessed normally. When a client sends a request to a load balancing device, the device extracts the address of a server from the list of available servers maintained according to some algorithm (such as linear polling, load by weight, load by traffic, etc.) and forwards it.

Client load balancing: the biggest difference between client load balancing and server load balancing lies in the location of the service list mentioned above. In client load balancing, all client nodes maintain the list of servers they want to access. The list of these servers comes from the service registry, such as Eureka server described in the previous chapter. Similar to the server-side load balancing architecture, the client-side load balancing also needs heartbeat to maintain the health of the server-side list, but this step needs to be completed in cooperation with the service registry. In the service governance framework implemented by Spring Cloud, the ribbon automatic integration configuration for each service governance framework will be created by default, such as org. Springf in Eureka ramework.cloud . netfl IX. Ribbon. Eureka. Ribboneure kaautoconfiguration, org. Springframework. Cloud. Consumer. Discovery In practice, we can check the implementation of these two classes to find their configuration details to help us better use it.
Through the encapsulation of Spring Cloud Ribbon, it is very simple for us to use the client-side load balancing call in the microservice architecture, which only needs the following two steps:

Step 1: the service provider only needs to start multiple service instances and register to - one registry or multiple associated service registries.
Step 2: the service consumer calls the service-oriented interface directly by calling the RestTemplate decorated by the @ LoadBalanced annotation.

In this way, we can realize the high availability of the service provider and the load balancing call of the service consumer (the ribbon load balancing tool of the client).

Section 2: how ribbon works

Spring Cloud Ribbon is a client-side load balancing tool based on HTTP and TCP, which is implemented based on the netflixribon framework. Then through the encapsulation of Spring Cloud, it becomes the Spring Cloud Ribbon. Spring Cloud Ribbon provides load balancing and retrying functions of the client, and its underlying layer uses RestTemplate to call Rest api. Let's talk about how RestTemplate works.

1. Working principle of remote call of resttemplate:
RestTemplate is a Rest remote calling tool provided by StringBoot, and it is also a RestTemplate class API. Every interface is a service.
RestTemplate class. Its common methods are:
1. getForObject() - execute get request (send get request to server side)
2. postForObject() - execute post request (send post request to server side)

Then we know that the execution process of the web application system structure we learned before is that the browser directly accesses the server background service. A process is shown in the following figure:

Then today we learned the RestTemplate remote call tool class, we can use RestTemplate to realize the remote client call function. Now we write a Demo project to demonstrate Spring Cloud remote call
The call schematic is as follows:

Section 3: RestTemplate execution remote call case

Next, we do not use ribbon, but use RestTemplate alone to perform remote calls:
Step 1: create a new ribbon Project
Step 2: pom.xml
Step 3: application.yml
Step 4: main program
Step 5: controller
Step 6: start and access the test

Step 1: create a new ribbon Project


Step 2: pom.xml

ribbon dependency already included in Eureka client

SP01 commons dependency needs to be added

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>cn.tedu</groupId> <artifactId>sp06-ribbon</artifactId> <version>0.0.1-SNAPSHOT</version> <name>sp06-ribbon</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <spring-cloud.version>Hoxton.SR5</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <!-- exclude eureka Back to me xml file format,Direct return json format Put this jar File exclusion,this jar The package software will return the returned result as xml file.--> <exclusions> <exclusion> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>cn.tedu</groupId> <artifactId>sp01-commons</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> </repository> </repositories> </project>

Step 3: application.yml

application.yml

spring: application: name: ribbon server: port: 3001 eureka: client: service-url: defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka

Step 4: main program

main program

Create RestTemplate instance

RestTemplate is a tool class used to call other microservices. It encapsulates remote calling code and provides a set of template methods for remote calling, such as getForObject(), postForObject()

package cn.tedu.sp06; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @EnableDiscoveryClient @SpringBootApplication public class Sp06RibbonApplication { //Create a RestTemplate instance and store it in the spring container @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(Sp06RibbonApplication.class, args); } }

Step 5: RibbonController

RibbonController

package cn.tedu.sp06.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import cn.tedu.sp01.pojo.Item; import cn.tedu.sp01.pojo.Order; import cn.tedu.sp01.pojo.User; import cn.tedu.web.util.JsonResult; @RestController public class RibbonController { @Autowired private RestTemplate rt; @GetMapping("/item-service/") public JsonResult<List<Item>> getItems(@PathVariable String orderId) { //Send a get request to the specified microservice address and get the return result of the service // Placeholder, filled with orderId return rt.getForObject("http://localhost:8001/", JsonResult.class, orderId); } @PostMapping("/item-service/decreaseNumber") public JsonResult decreaseNumber(@RequestBody List<Item> items) { //Send post request return rt.postForObject("http://localhost:8001/decreaseNumber", items, JsonResult.class); } ///////////////////////////////////////// @GetMapping("/user-service/") public JsonResult<User> getUser(@PathVariable Integer userId) { return rt.getForObject("http://localhost:8101/", JsonResult.class, userId); } @GetMapping("/user-service//score") public JsonResult addScore( @PathVariable Integer userId, Integer score) { return rt.getForObject("http://localhost:8101//score?score=", JsonResult.class, userId, score); } ///////////////////////////////////////// @GetMapping("/order-service/") public JsonResult<Order> getOrder(@PathVariable String orderId) { return rt.getForObject("http://localhost:8201/", JsonResult.class, orderId); } @GetMapping("/order-service") public JsonResult addOrder() { return rt.getForObject("http://localhost:8201/", JsonResult.class); } }

Step 6: start and access the test

Start the service according to the figure below, and launch the access test on the client

Client access link URL:

http://eureka1:2001

http://localhost:3001/item-service/35
http://localhost:3001/item-service/decreaseNumber
Using postman, POST sends data in the following format:
[{"id":1, "name":"abc", "number":23},{"id":2, "name":"def", "number":11}]

http://localhost:3001/user-service/7
http://localhost:3001/user-service/7/score?score=100

http://localhost:3001/order-service/123abc
http://localhost:3001/order-service/

Section 4: RestTemplate class details

RestTemplate details
In the previous section, we have implemented the client-side load balancing function of service consumers by introducing Ribbon. Readers can get the experimental examples by looking at the section "service discovery and consumption" in Chapter 3. Among them, we use a very useful object RestTemplate. This object will use the Ribbon's automatic configuration. At the same time, by configuring @ LoadBalanced, it can also enable client load balancing. Previously, we demonstrated the simplest service access through RestTemplate. Next, we will introduce the service call implementation of RestTemplate for several different request types and parameter types in detail.

First point: request analysis of RestTemplate class

First: GET request
Second: post request
Third: put request
Fourth: delete request

Second point: RestTemplate source code parsing

RestTemplate source code analysis

Chapter 11: ribbon load balancing and retry (client load balancing tool)

Section I: ribbon load balancing schematic diagram

1.ribbon client load balancing execution flow chart

2.ribbon client load balancing framework

3.ribbon load balancing schematic diagram

Section 2: explanation of ribbon load balancing function cases

Step 1: modify sp06 Ribbon Project
Step 2: add ribbon start dependency (optional)
Step 3: set @ LoadBalanced for RestTemplate
Step 4: set access path to service id

Section 3: explanation of ribbon retry function cases

Step 1: in project 06, add the ribbon start-up dependency;
Step 2: add @ LoadBalanced / / load balancing annotation to the startup class
Step 3: on the RibbonController class of the client load balancing control layer, modify the access path to the name / id of the server after tomorrow

Key issues:

The security software of tinder can kill the window information of computer

13 June 2020, 06:18 | Views: 1798

Add new comment

For adding a comment, please log in
or create account

0 comments