Hello, today I would like to share Spring Cloud with you. Please take out your notebook and write it down.
Spring Cloud
1. Introduction
1. The meaning of
Spring Cloud is a one-stop solution for microservice system architecture. In normal times, we need to do operations such as service discovery registration, configuration center, message bus, load balancing, circuit breaker, data monitoring and so on in the process of building microservices. Spring Cloud provides us with a set of simple programming model. It makes it easy to build microservice projects based on Spring Boot.
2. Relationship with SpringBoot
SpringBoot focuses on developing individual microservices.
SpringCloud integrates individual microservices and manages them.
SpringBoot can be used independently of SpringCloud, and SpringCloud cannot be used without SpringBoot.
Bottom line: SpringBoot focuses on developing individual microservices. SpringCloud focuses on global service governance.
2.Eureka service registration and discovery
1. Introduction
Eureka is a component in the Spring Cloud responsible for service registration and discovery.
Eureka consists of multiple instances (service instances), which 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 A Service Provider registers its Service with Eureka so that Service consumers can find it
The Service Consumer obtains a list of registered services from Eureka and is able to consume services
2. Implementation process
1. The package
org.springframework.cloud
spring-cloud-starter-eureka-server
1.4.6. RELEASE
Normally, import the package. However, if the following error is reported during runtime, you can import the following package to solve the problem.
Java. Lang. TypeNotPresentException: Type javax.mail. XML. Bind. The JAXBContext not present / / wrong
2. Create the applcation. XML file
3. Enable the service
Then visit http://localhost:7001/ and the following screen will appear.
Default is null because no services have been registered yet.
4. Service registration
Guide packages in service items. Note: the package imported here is not the same as above.
Add the configuration in application.xml
Open the service
Visit http://localhost:7001/ again
5. Self-protection mechanisms
The red font in the image above is the self-protection mechanism in Eureka. The meanings are as follows.
When a microservice becomes unusable, Eureka does not immediately clean it up and still saves information about the microservice.
3. Differences between Eureka and zooKeeper
Theory of CAP
C (Consistency) : strong Consistency
A (Availability) : Availability
P (Partition tolerance) : fault tolerance of a Partition
It is impossible for A distributed system to satisfy all three principles, and P (partition fault tolerance) must be guaranteed, so you have to choose between A and C.
Zookeeper is CP.
Eureka is AP.
Conclusion: Eureka can cope well with a network failure that causes some nodes to lose contact, rather than paralyzing the entire registration service like ZooKeeper.
3.Ribbon
1. Introduction
Spring Cloud Ribbon is a tool for client load balancing.
Load Balance refers to balancing loads (work tasks) and allocating them to multiple operation units, such as FTP server, Web server, enterprise core application server, and other main task servers, to cooperatively complete work tasks.
In simple terms, users’ requests are evenly distributed across multiple servers to achieve high availability (HA) of the system.
2. Implementation process
Note: We use the Ribbon on the client side.
1. The package
2. Create the applcation. XML file
3. Enable the service
4. Use the Ribbon
We are using the RestTemplate for URL hops, so we can use the @loadBalanced annotation to implement load balancing.
Change the URl here to the ID in Eureka.
Visit http://localhost:8080/customer/dept/list, each time to refresh, read a different service.
4.Feign
1. Introduction
It’s load balancing, just like the Ribbon.
However, Ribbon is accessed through microservice names, and Feign is accessed through interfaces and annotations.
Feign integrated with Rubbon.
2. Implementation steps
1. The package
Import both in springCloud-API and SpringCloud-Feign projects.
org.springframework.cloud
spring-cloud-starter-feign
1.4.6. RELEASE
2. Write the Service in the Spring Cloud-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 Spring Cloud-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 meltdown
1. Serve avalanche
Suppose there is the following call chain
In this case, the traffic of Service A fluctuates greatly and often increases unexpectedly! In this case, even if Service A can handle the request, Service B and Service C may not be able to handle the unexpected request.
At this point, if Service C becomes unavailable because it can no longer handle requests. Requests to Service B will also block, slowly depleting the thread resources of Service B, and Service B will become unavailable. Then Service A becomes unavailable, as shown in the figure below
As shown in the figure above, a service failure leads to a service failure of the entire link, which is called a service avalanche.
2. What is Hystrix
Hystrix is a system to deal with distributed delay, and fault tolerance of the open source library, in a distributed system, many rely on inevitably call fails, such as overtime, abnormal Hystrix can guarantee in the case of a dependency problem, won’t cause the overall service failure, avoid cascading failure, in order to improve the flexibility of a distributed system.
The “breaker” itself is a kind of switching device. When a service unit fails, through the fault monitoring of the breaker (similar to blowing a fuse), ** returns to the caller an expected and manageable FallBack response (FallBack) of the service, rather than waiting for a long time or throwing an exception that the calling method cannot handle. ** This ensures that the threads of service callers are not tied up unnecessarily for long periods of time, thus preventing failures from spreading and even avalanches in a distributed system.
What can be done
Service fusing
Service degradation
3. Service circuit breaker
Service circuit breaker is a micro – service link protection mechanism against avalanche effect.
When a microservice of the link is unavailable or the response time is too long, the service is degraded and the invocation of the microservice on the node is interrupted quickly
Error response message quickly returned.
Restore the call link after detecting that the microservice invocation response of this node is normal.
In the SpringCloud framework, circuit breakers are implemented through Hystrix. Hystrix monitors calls between microservices and triggers a circuit breaker when the number of failed calls reaches a threshold of 20 in five seconds.
The comment on the circuit breaker mechanism is @hystrixCommand.
4. Service fusing implementation steps
1. Import dependencies
org.springframework.cloud
spring-cloud-starter-hystrix
1.4.6. RELEASE
2. Modify the Controller layer
Normally, if the query ID does not exist, a 500 screen is returned. After adding the @hystrixCommand annotation, the following method is called.
@RestController
public class DeptController {
@Autowired
private DeptService deptService;
@GetMapping(“/dept/get/{id}”)
@hystrixCommand (fallbackMethod = “hystrixGet”
public Dept queryDeptByid(@PathVariable(“id”) Long id){
Dept dept = deptService.queryByid(id);
if (dept==null)
Throw new RuntimeException(” Information could not be found!! “) );
return dept;
}
// Alternatives
public Dept hystrixGet(@PathVariable(“id”) Long id){
return new Dept()
.setDeptno(id)
.setdName (” no corresponding information -> @hystrix “)
.setDb_source(“no this database”);
}
}
3. Enable the Hystrix service
@enablecircuitbreaker // Add fuse breaker support
/ / start the class
@SpringBootApplication
@enableEurekaclient // Automatically register with Eureka after the service starts
@enablecircuitbreaker // Add fuse breaker support
public class DeptProvider_hystrix_8001 {
public static void main(String[] args) {
SpringApplication.run(DeptProvider_hystrix_8001.class,args);
}
}
4. Achieve results
5. Service degradation
1. Introduction
What is service degradation?
When the server pressure increases dramatically, according to the actual business situation and traffic, some services and pages are strategically not processed or processed in a simple way, so as to release server resources to ensure the normal or efficient operation of core transactions.
Application scenarios
When the overall load of the microservice architecture exceeds the preset upper threshold or the incoming traffic is expected to exceed the preset threshold, we can delay or suspend the use of some non-important or non-urgent services or tasks to ensure the normal operation of important or basic services.
2. Procedure
Create 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 closed “)
.setdb_source (” No data “);
}
@Override
public List queryAll() {
return null;
}
};
}
}
In the Service layer in SpringCloud-API
Application. Yml in the Spring Cloud-Customer-Feign project enables service degradation
Enable service degradation
feign:
hystrix:
enabled: true
When the server is running properly, users can access it normally. When the server is shut down manually or for other reasons, a message is displayed when users access the server. As shown in the figure below.
6. Distinction between service circuit breaker and service degradation
Service fusing
Perform operations on the server side
When a service times out or is abnormal, a fuse is triggered
There will be no intentional service circuit breaker
Service degradation
On the client
When a service is shut down, on the client side, we prepare a FallbackFactory that returns a default value.
Service degradation can be deliberately caused
7. Monitor DashBoard
Fuses monitoring in springCloud can help us know how many service interfaces are being called at a certain time and what state the circuit breaker is currently in.
1. Implement the monitoring function
Create a new project
Import dependence
org.springframework.cloud
spring-cloud-starter-hystrix
1.4.6. RELEASE
org.springframework.cloud
spring-cloud-starter-hystrix-dashboard
1.4.6. RELEASE
Changing the port Number
server:
port: 9001
Writing a startup class
@SpringBootApplication
@enablehystrixDashboard // Start 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
Note: this is the project that implements the service circuit breaker. Otherwise, there will be no page.
The premise
The monitoring package is imported into this project
org.springframework.boot
spring-boot-starter-actuator
Add a bean to the startup class
@Bean
public ServletRegistrationBean hystrixMetricsStreamServlet(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new HystrixMetricsStreamServlet());
registrationBean.addUrlMappings(“/actuator/hystrix.stream”);
return registrationBean;
}
When the server is running properly, users can access it normally. When the server is shut down manually or for other reasons, a message is displayed when users access the server. As shown in the figure below.
6. Distinction between service circuit breaker and service degradation
Service fusing
Perform operations on the server side
When a service times out or is abnormal, a fuse is triggered
There will be no intentional service circuit breaker
Service degradation
On the client
When a service is shut down, on the client side, we prepare a FallbackFactory that returns a default value.
Service degradation can be deliberately caused
7. Monitor DashBoard
Fuses monitoring in springCloud can help us know how many service interfaces are being called at a certain time and what state the circuit breaker is currently in.
1. Implement the monitoring function
Create a new project
Import dependence
org.springframework.cloud
spring-cloud-starter-hystrix
1.4.6. RELEASE
org.springframework.cloud
spring-cloud-starter-hystrix-dashboard
1.4.6. RELEASE
Changing the port Number
server:
port: 9001
Writing a startup class
@SpringBootApplication
@enablehystrixDashboard // Start 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
Note: this is the project that implements the service circuit breaker. Otherwise, there will be no page.
The premise
The monitoring package is imported into this project
org.springframework.boot
spring-boot-starter-actuator
Add a bean to 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 it according to the following figure
If the following page is displayed, the configuration is successful. For more information on this page, go online and do your own research.
6.Zuul Routing gateway
1. Introduction
Zuul includes two main functions for routing and filtering requests:
The routing function is responsible for forwarding external requests to specific microservice instances, which is the basis for achieving unified access to external access
The filter function is responsible for intervening in the process of request processing, which is the basis of request verification, service aggregation and other functions
Zuul and Eureka integrate, register Zuul itself as an application under Eureka service governance, and obtain messages of other microservices from Eureka. In other words, access to microservices in the future will be obtained through Zuul jump.
Note: The Zuul service will eventually be registered with Eureka
Provides three functions: proxy, route, and filtering
2. Implementation steps
1. Import dependencies
org.springframework.cloud
spring-cloud-starter-zuul
1.4.6. RELEASE
Configure the application.yml file
Zuul needs to be registered with Eureka, so You need to configure Eureka
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 all services *
3. Write startup classes
@SpringBootApplication
@enableZuulProxy // Enable the proxy
public class ZuulApplication_9527 {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication_9527.class,args);
}
}
3. Achieve results
Previously, we accessed it in the following way. This will reveal some information about the project.
We can now access it using the Zuul configured port number, where SpringCloud-provider-Dept is the name of the Spring configuration.
If you don’t want access through this, you can configure it yourself.
The effect is shown below
7.SpringCloud Config
1. Introduction
SpringCloud Config provides centralized external configuration support for microservices in the microservices architecture, providing a centralized external configuration for all environments of different microservices applications.
SpringCloud Config is divided into two parts: server and client.
The server, also known as the distributed configuration center, is an independent micro-service application that connects to the configuration server and provides an access interface for the client to obtain configuration information, encrypt/decrypt information, etc.
The client manages application resources and business-related configurations through the specified configuration center, and obtains and loads configuration information from the configuration center when starting up. By default, the configuration server uses Git to store configuration information, which is helpful for version management of environment configurations. Git client tools can be used to easily manage and access configuration content.
When the configuration file in a system is changed, 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 file of all systems in the microservice, and it can also realize that when the configuration file changes, The system automatically updates and obtains new configurations.
2. Configure the server
1. Preparation
Create a repository on GitHub or Gitee to put your own files in.
2. Import dependencies
org.springframework.cloud
spring-cloud-config-server
2.1.1. RELEASE
3. Compile the application.yml file
server:
port: 3344
spring:
application:
name: springcloud-config-server
Connecting remote Configuration
cloud:
config:
server:
git:
Uri: gitee.com/infiniteSta… The address of the project on gitee
4. Write startup classes
@SpringBootApplication
@EnableConfigServer
public class Config_server_3344 {
public static void main(String[] args) {
SpringApplication.run(Config_server_3344.class,args);
}
}
5. Test
The remote configuration file was successfully accessed.
3. Configure the client
1. Import dependencies
org.springframework.cloud
spring-cloud-starter-config
2.1.1. RELEASE
2. Compile the application.yml file
The application. Yml file can also be replaced by the bootstrap.yml file. The difference is that bootstrap.yml is a system-level configuration and application.
System-level configuration
spring:
cloud:
config:
Name: config-client # Name of the resource you want to get from Git
uri: http://localhost:3344
Profile: dev # Optional version
Label: master # Select branch
3. Write startup classes
@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 result
Well, that’s all for today’s article, hoping to help those of you who are confused in front of the screen