GitHub was removed overnight! How strong is the new Spring Cloud manual produced by Ali P8?

GitHub was removed overnight! How strong is the new Spring Cloud manual produced by Ali P8?

Hello, today I will share Spring Cloud with all children's shoes, please take out a small book and write it down!

Spring Cloud

1 Introduction

1. Meaning

Spring Cloud is a one-stop solution for microservice system architecture. In the process of building microservices, we need to do operations such as service discovery registration, configuration center, message bus, load balancing, circuit breakers, data monitoring, etc., while Spring Cloud Provides us with a simple programming model, so that we can easily implement the construction of microservice projects on the basis of Spring Boot.

2. Relationship with SpringBoot

SpringBoot focuses on the development of individual individual microservices.

SpringCloud integrates and manages individual microservices.

SpringBoot can be used independently without SpringCloud, and SpringCloud cannot do without SpringBoot.

Summary: SpringBoot focuses on the development of individual individual microservices. SpringCloud focuses on global service governance.

2. Eureka service registration and discovery

1 Introduction

Eureka is a component responsible for service registration and discovery in spring cloud.

Eureka consists of multiple instances (service instances). These service instances can be divided into two types: Eureka Server and Eureka Client. For ease of understanding, we divide Eureka client into Service Provider and Service Consumer.

Eureka Server provides service registration and discovery

Service Provider service provider, register its own service to Eureka, so that service consumers can find

Service Consumer service consumer, obtain the list of registered services from Eureka, so as to be able to consume services

2. Implementation process

1. Guide package

org.springframework.cloud

spring-cloud-starter-eureka-server

1.4.6.RELEASE

If it is normal, just import this package. But if the error below is reported when running, you can import the package below to solve it.

java.lang.TypeNotPresentException: Type javax.xml.bind.JAXBContext not present//reported error

2. Write applcation.xml file

3. Turn on the service

After visiting http://localhost:7001/ , the following interface will appear.

The default is empty, because there is no service registered yet.

4. Service Registration

Guide the package in the service item. Note: The package imported here is different from the one above.

Add configuration in application.xml

Open service

Visit http://localhost:7001/again

5. Self-protection mechanism

The red font in the picture above is the self-protection mechanism in Eureka. The meaning is as follows.

When a microservice is unavailable, eureka will not clean it up immediately, and will still save the information of the microservice.

3. The difference between Eureka and zooKeeper

CAP theory

C (Consistency): strong consistency

A (Availability): Availability

P (Partition tolerance): Partition tolerance

A distributed system cannot satisfy the three principles at the same time, and P (partition fault tolerance) must be guaranteed, so only one of A and C can be selected.

zookeeper is CP.

Eureka is AP.

Conclusion: Eureka can deal with the situation that some nodes lose contact due to network failures, and will not paralyze the entire registration service like zookeeper.

3.Ribbon

1 Introduction

Spring Cloud ribbon is a tool to achieve client load balancing.

Load balancing, the English name is Load Balance, which means to balance and distribute the load (work tasks) to multiple operation units for operation, such as FTP server, Web server, enterprise core application server and other main task servers, etc. So as to complete the work task together.

Simply put, it is to evenly distribute the user's requests to multiple servers, so as to achieve the system's HA (high availability).

2. Implementation process

Note: We are using Ribbon on the client side.

1. Guide package

2. Write applcation.xml file

3. Turn on the service

4. Use Ribbon

We use RestTemplate to implement URL redirection, so add the annotation @LoadBalanced above to achieve load balancing.

Modify the URl here to the id in Eureka.

Visit http://localhost:8080/customer/dept/list , and every time you refresh, the read service is different.

4. Feign

1 Introduction

Like Ribbon, it also performs load balancing.

However, Ribbon is accessed through the microservice name, and Feign is accessed through interfaces and annotations.

Feign integrates Rubbon.

2. Implementation steps

1. Guide package

Imported in springcloud-api and springcloud-feign projects.

org.springframework.cloud

spring-cloud-starter-feign

1.4.6.RELEASE

2. Write service in the springcloud-api project

Just add this annotation @FeignClient

@Component

@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT")

public interface DeptClientService {

@PostMapping("/dept/add")

boolean addDept(Dept dept);

@GetMapping("/dept/get/{id}")

Dept queryByid(@PathVariable("id") Long id);

@GetMapping("/dept/list")

List queryAll();

}

3. Write Controlelr in the springcloud-feign project

@RestController

public class CustomerController {

@Autowired

private DeptClientService deptClientService=null;

@RequestMapping("/customer/dept/get/{id}")

public Dept get(@PathVariable("id")Long id){

return deptClientService.queryByid(id);

}

@RequestMapping("/customer/dept/add")

public boolean add(Dept dept){

return deptClientService.addDept(dept);

}

@RequestMapping("/customer/dept/list")

public List list(){

return deptClientService.queryAll();

}

}

4. Modify the main program

5. Start the project

The result is the same as using Ribbon+RestTemplate. I think this method is simpler.

5. Hystrix service circuit breaker

1. Service avalanche

Suppose there is the following call chain

At this time, the traffic of Service A fluctuates greatly, and the traffic often increases suddenly! So in this case, even if Service A can handle the request, Service B and Service C may not be able to handle the sudden request.

At this point, if Service C cannot resist the request, it becomes unavailable. Then Service B's request will also be blocked, slowly exhausting Service B's thread resources, Service B will become unavailable. Immediately afterwards, Service A will also be unavailable. This process is shown in the following figure

As shown in the figure above, a service failure causes the entire link to fail. We call it a service avalanche.

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 will inevitably fail to call, such as timeouts and exceptions. Hystrix can guarantee that if a dependency fails, it will not Cause the overall service to fail and avoid cascading failures to improve the resilience of the distributed system.

The "circuit breaker" itself is a kind of switching device. When a service unit fails, through the fault monitoring of the circuit breaker (similar to a blown fuse), ** returns a service expected and processable alternative response to the caller ( FallBack), instead of waiting for a long time or throwing exceptions that cannot be handled by the calling method, **This ensures that the thread of the service caller will not be occupied for a long time and unnecessary, thus avoiding failures in the distributed system The spread in the world, and even an avalanche.

What can be done

Service fuse

Service degradation

3. Service fusing

Service fuse is a micro-service link protection mechanism against the avalanche effect.

When a certain microservice of the link is unavailable or the response time is too long, the service will be degraded, and then the call of the microservice of the node will be fuse.

Quickly return wrong response information.

When it is detected that the microservice call response of the node is normal, the call link is restored.

In the SpringCloud framework, the fuse mechanism is implemented by Hystrix. Hystrix will monitor the status of calls between microservices. When the failed calls reach a certain threshold, the fuse mechanism will be activated for 20 failed calls within 5 seconds.

The annotation of the fuse mechanism is @HystrixCommand.

4. Service circuit breaker implementation steps

1. Import dependencies

org.springframework.cloud

spring-cloud-starter-hystrix

1.4.6.RELEASE

2. Modify the Controller layer

Under normal circumstances, if the queried id does not exist, a 500 interface will be returned. After adding @HystrixCommand annotation, the following method will be called.

@RestController

public class DeptController {

@Autowired

private DeptService deptService;

@GetMapping("/dept/get/{id}")

@HystrixCommand(fallbackMethod = "hystrixGet")//Call the method below if the call fails

public Dept queryDeptByid(@PathVariable("id") Long id){

Dept dept = deptService.queryByid(id);

if (dept==null)

throw new RuntimeException("The information could not be found!!!");

return dept;

}

//Options

public Dept hystrixGet(@PathVariable("id") Long id){

return new Dept()

.setDeptno(id)

.setDname("No corresponding information -> @Hystrix")

.setDb_source("no this database");

}

}

3. Turn on the Hystrix service

@EnableCircuitBreaker//Add support for circuit breaker

//Start class

@SpringBootApplication

@EnableEurekaClient//Automatically register to Eureka after the service starts

@EnableCircuitBreaker//Add support for circuit breaker

public class DeptProvider_hystrix_8001 {

public static void main(String[] args) {

SpringApplication.run(DeptProvider_hystrix_8001.class,args);

}

}

4. Realize the effect

5. Service degradation

1 Introduction

What is service degradation?

When server pressure increases sharply, according to actual business conditions and traffic, some services and pages are strategically not processed or processed in a simple manner, thereby freeing server resources to ensure normal or efficient operation of core transactions.

Application scenario

When the overall load of the entire microservice architecture exceeds the preset upper threshold or the upcoming traffic is expected to exceed the preset threshold, in order to ensure the normal operation of important or basic services, we can set some unimportant or non-urgent services The service or task of the service is delayed or suspended.

2. Use steps

Create the FallbackFactory class

@Component

public class DeptClientServiceFailbackFactory implements FallbackFactory {

@Override

public DeptClientService create(Throwable throwable) {

return new DeptClientService() {

@Override

public boolean addDept(Dept dept) {

return false;

}

@Override

public Dept queryByid(Long id) {

return new Dept()

.setDeptno(id)

.setDname("Service is closed")

.setDb_source("No data");

}

@Override

public List queryAll() {

return null;

}

};

}

}

In the service layer in springcloud-api

Open the service downgrade in application.yml in the springcloud-customer-feign project

#Open service downgrade

feign:

hystrix:

enabled: true

When the server is working normally, users can access it normally. When the server is shut down artificially or due to other reasons, a prompt message will appear when the user accesses it. As shown below.

6. The difference between service fuse and service degradation

Service fuse

Operate on the server

A certain service is timed out or abnormal, causing a fuse to be equivalent

Will not deliberately cause service fuse

Service degradation

On the client side

When a service is closed, at this time on the client side, we will prepare a FallbackFactory and return a default value (default value).

Can deliberately cause service degradation

7. DashBoard monitoring

It belongs to the fuse monitoring in springCloud, which can help us know the status of a single service interface being called within a certain period of time and the current state of the circuit breaker.

1. Realize the monitoring function

Create a new project

Import dependencies

org.springframework.cloud

spring-cloud-starter-hystrix

1.4.6.RELEASE

org.springframework.cloud

spring-cloud-starter-hystrix-dashboard

1.4.6.RELEASE

Modify port number

server:

port: 9001

Write startup class

@SpringBootApplication

@EnableHystrixDashboard//Open the monitoring page

public class DeptCustomerDashboard_9001 {

public static void main(String[] args) {

SpringApplication.run(DeptCustomerDashboard_9001.class,args);

}

}

2. Configure monitoring information on the server side

Note: It is a project that realizes service fusing. Otherwise, there will be no pages behind.

premise

The monitored package is imported into this project

org.springframework.boot

spring-boot-starter-actuator

Add a bean in the startup class

@Bean

public ServletRegistrationBean hystrixMetricsStreamServlet(){

ServletRegistrationBean registrationBean = new ServletRegistrationBean(new HystrixMetricsStreamServlet());

registrationBean.addUrlMappings("/actuator/hystrix.stream");

return registrationBean;

}

When the server is working normally, users can access it normally. When the server is shut down artificially or due to other reasons, a prompt message will appear when the user accesses it. As shown below.

6. The difference between service fuse and service degradation

Service fuse

Operate on the server

A certain service is timed out or abnormal, causing a fuse to be equivalent

Will not deliberately cause service fuse

Service degradation

On the client side

When a service is closed, at this time on the client side, we will prepare a FallbackFactory and return a default value (default value).

Can deliberately cause service degradation

7. DashBoard monitoring

It belongs to the fuse monitoring in springCloud, which can help us know the status of a single service interface being called within a certain period of time and the current state of the circuit breaker.

1. Realize the monitoring function

Create a new project

Import dependencies

org.springframework.cloud

spring-cloud-starter-hystrix

1.4.6.RELEASE

org.springframework.cloud

spring-cloud-starter-hystrix-dashboard

1.4.6.RELEASE

Modify port number

server:

port: 9001

Write startup class

@SpringBootApplication

@EnableHystrixDashboard//Open the monitoring page

public class DeptCustomerDashboard_9001 {

public static void main(String[] args) {

SpringApplication.run(DeptCustomerDashboard_9001.class,args);

}

}

2. Configure monitoring information on the server side

Note: It is a project that realizes service fusing. Otherwise, there will be no pages behind.

premise

The monitored package is imported into this project

org.springframework.boot

spring-boot-starter-actuator

Add a bean in the startup class

@Bean

public ServletRegistrationBean hystrixMetricsStreamServlet(){

ServletRegistrationBean registrationBean = new ServletRegistrationBean(new HystrixMetricsStreamServlet());

registrationBean.addUrlMappings("/actuator/hystrix.stream");

return registrationBean;

}

Start the project and configure as shown below

After entering, the following interface appears, indicating that the configuration is successful. For more information about this page, please check the information online.

6. Zuul routing gateway

1 Introduction

Zuul contains two main functions for request routing and filtering:

The routing function is responsible for forwarding external requests to specific microservice instances, which is the basis for achieving a unified entry for external access

The filter function is responsible for intervening in the processing of the request, and is the basis for realizing request verification, service aggregation and other functions

Zuul and Eureka are integrated to register Zuul itself as an application under Eureka service governance, and at the same time obtain other microservice messages from Eureka, that is, future access to microservices is obtained after Zuul jumps.

Note: Zuul service will eventually be registered into Eureka

Provides three functions: proxy + routing + filtering

2. Implementation steps

1. Import dependencies

org.springframework.cloud

spring-cloud-starter-zuul

1.4.6.RELEASE

2. Configure the application.yml file

Zuul needs to be registered in Eureka, so Eureka needs to be configured

server:

port: 9527

spring:

application:

name: springcloud-zuul

eureka:

client:

service-url:

defaultZone: http://localhost:7001/eureka/

instance:

instance-id: springcloud-zuul-9527

prefer-ip-address: true # Display the real ip address

info:

app.name: dzsq-springcloud

company.name: blog.dzsq.com

zuul:

routes:

mydept.serviceId: springcloud-provider-dept

mydept.path:/mydept/**

ignored-services: springcloud-provider-dept #Ignore the original path and ignore all services "*"

3. Write the startup class

@SpringBootApplication

@EnableZuulProxy//Enable the proxy

public class ZuulApplication_9527 {

public static void main(String[] args) {

SpringApplication.run(ZuulApplication_9527.class,args);

}

}

3. Realize the effect

Previously, we used the following figure to visit. This will expose some information about the project.

Now we can use the port number configured by Zuul to access, where springcloud-provider-dept is the name of the configured Spring.

If you don't want to access through this, you can configure it yourself.

Results as shown below

7.SpringCloud Config

1 Introduction

SpringCloud Config provides centralized external configuration support for microservices in the microservice architecture, and provides a centralized external configuration for all environments of different microservice applications.

SpringCloud Config is divided into two parts: server and client.

The server is also called a distributed configuration center. It is an independent microservice application that is used to connect to the configuration server and provide access interfaces for the client to obtain configuration information, encrypt/decrypt information, and so on.

The client manages application resources and business-related configuration content through the designated 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 the environment configuration, and the git client tool can be used to conveniently manage and access the configuration content.

When the configuration file in a system changes, we need to restart the service to make the new configuration file take effect. Spring cloud config can realize the unified management of the configuration files of all systems in the microservice, and it can also realize the current When the configuration file changes, the system will automatically update to obtain the new configuration.

2. Server configuration

1. Preparation

Create a repository on GitHub or Gitee and put in one of your own files.

2. Import dependencies

org.springframework.cloud

spring-cloud-config-server

2.1.1.RELEASE

3. Write application.yml file

server:

port: 3344

spring:

application:

name: springcloud-config-server

Connect remote configuration

cloud:

config:

server:

git:

uri: gitee.com/infiniteSta ... The address of the project on #gitee

4. Write the startup class

@SpringBootApplication

@EnableConfigServer

public class Config_server_3344 {

public static void main(String[] args) {

SpringApplication.run(Config_server_3344.class,args);

}

}

5. Test

Successfully accessed the remote configuration file.

3. Client configuration

1. Import dependencies

org.springframework.cloud

spring-cloud-starter-config

2.1.1.RELEASE

2. Write application.yml file

The application.yml file can also be replaced by the bootstrap.yml file. The difference is that bootstrap.yml is the system-level configuration, and application.yml is the user-level configuration.

#System level configuration

spring:

cloud:

config:

name: config-client #The name of the resource that needs to be obtained from git

uri: http://localhost:3344

profile: dev #selected version

label: master #Select branch

3. Write the startup class

@SpringBootApplication

public class Config_client_3355 {

public static void main(String[] args) {

SpringApplication.run(Config_client_3355.class,args);

}

}

4. Test in the controller layer

@RestController

public class ConfigController {

@Value("${eureka.client.service-url.defaultZone}")

private String eureka;

@RequestMapping("/config")

public String config(){

return "eureka"+eureka;

}

}

5. Running results

Alright, that s all for today s article, I hope to help you who are confused in front of the screen