SpringCloud XVI What Hystrix breaker yes. Services blown.

What ①Hystrix breaker yes.

hystrix circuit breakers, also known as fuses. Responsible for springcloud fuse inside the service, service degradation process. hystrix is ​​abnormal when a program or service for a long time to call a micro inappropriate inappropriate, did not respond for a long time, overtime, then the program how to do.

Problems faced by distributed systems:

Problems faced by distributed systems:
application of complex distributed architecture dozens of dependencies Each dependency at some point will inevitably fail.

 

Services avalanche
when calling between a plurality of micro services, assume micro-micro-service service A calls B and C service micro, micro and micro-service B and C service call other micro service, which is called "fan-out." Call a micro-services link on the fan-out if the response time is too long or is not available, the call to the micro-service A will take up more and more system resources, thereby causing the system to crash, so-called "avalanche effect."

For high traffic, a single back-end dependence may lead to all resources on all servers are saturated in a few seconds. Worse than failure, these applications may also cause a delay between the service increases, the backup queue, threads, and other nervous system resources, resulting in the entire system more cascading failure. Which indicate a need for isolation and fault management and delay, so that a single failed dependencies, can not cancel the entire application or system.

 

Note: For general service dependent protection are mainly 3 solutions:

(1) fusing mode: This mode is mainly blown reference circuit, if a line voltage is too high, blown fuses and prevent fires. Into our system, if a target service invocation slow or there is a lot of time expires, blown to call the service, the request for a subsequent call, do not continue to call the target service, direct return, quick release resources. If the goal is to restore the situation improved service calls.

(2) Isolation mode: This mode of the system as requested by the same type into one island, when the island is a fire, the less light will not affect the other islands. For example, may be used for different types of requests to the thread pool resource isolation, independently of each other for each type of request, if one type of resource exhaustion request thread, then the type of the subsequent request returned directly, instead of calling up resources. This mode uses scene very much, for example, will open a service, for important services use to deploy a separate server, or again recently to promote multi-center.

(3) limiting mode: mode and the above-described fuse isolation mode belong to a fault-tolerant processing mechanism after an error, while the current limiting mode may be referred to as a preventive mode. Limiting mode is primarily set in advance QPS highest threshold value for each type of request, if the above threshold is set to return directly to the request, instead of calling up resources. This model does not solve the problem of service depends, can only solve the overall problem of resource allocation system, because the request has not been limiting still likely to cause an avalanche effect.
 
 
 
What is it hystrix:

Hystrix is a distributed system for processing delays and fault-tolerant open source libraries, distributed systems, many rely inevitably call fails, such as overtime, abnormal, Hystrix can guarantee in the case of a dependency problem, It will not result in an overall service to fail, to avoid cascading failures, in order to improve the flexibility of distributed systems.
 
"Breaker" is a switching apparatus itself, when a service unit fails, the fault monitoring circuit breaker (similar to a blown fuse), the caller (service consumer) is returned to a line with expectations, can be prepared by treatment of selected response (FallBack), rather than the long wait or throw caller unhandled exception, thus ensuring the caller to the service (the service consumer) thread will not be long, unnecessarily occupied, thus avoiding failure to spread in a distributed system, and even avalanches.
 

 

② service fuse.

hystrix can you do?

First, the service degradation

Note: Hystrix service degradation, in fact, a single processing thread pool thread barrier, to prevent a single thread request too long, leading to long-term resources occupied and not released, causing the thread pool is completely occupied quickly, crash the service.
Hystrix can solve the following problems:
1. Request timed out downgrade, lack of resources thread downgrade, after the downgrade can return custom data
2. thread pool isolation downgrade, distributed services for different services use different thread pool, so independently of each other
3 automatic triggering degraded and recovery
4. implement combined request buffer and the request

 

 

Second, the service fuse

Note: fusing mode: This mode is mainly blown reference circuit, if a line voltage is too high, blown fuses and prevent fires. Into our system, if a target service invocation slow or there is a lot of time expires, blown to call the service, the request for a subsequent call, do not continue to call the target service, direct return, quick release resources. If the goal is to restore the situation improved service calls.

 

Third, limiting service

Note: The current limit mode is mainly set in advance highest QPS threshold for each type of request, if above the threshold set by the direct return to the request, instead of calling up resources. This model does not solve the problem of service depends, can only solve the overall problem of resource allocation system, because the request has not been limiting still likely to cause an avalanche effect.

Fourth, near real-time monitoring

Fives,. . . . . .

Information on the official website: https://github.com/Netflix/Hystrix/wiki/How-To-Use

 

Hystrix breaker: ideas:

1 maven ---------- GAV coordinates

2 corresponds to a new annotation tag technology component

                  2.1              @EnableXXXXXXXX

 

What service is blown:

Services blown
fuse mechanism is to respond to a micro service link protection mechanism avalanche effect.
When a micro-fan-out link service is unavailable or response time is too long, it will downgrade the service, and then blown call the micro-node service, the quick return "wrong" response information. After detecting the micro-node service call response call resume normal link. Hystrix implemented in the framework of SpringCloud by fusing mechanism. Hystrix will monitor the situation between micro service calls, failed calls when a certain threshold value, the default is the call fails 20 times within five seconds will start fusing mechanism. Notes fuse mechanism is @HystrixCommand.
 

The first step: Reference microservicecloud-provider-dept-8001, to create a sub-module project microservicecloud-provider-dept-hystrix-8001, note: the service provider side. client is a client-side service that is on the consumer side, such as ribbon and feign. The hystrix is ​​the service provider side.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Step two: Modify the pom file:

Sub-project microservicecloud-provider-dept-hystrix-8001 pom file modification of the contents are:

 <!--  hystrix -->
   <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-hystrix</artifactId>
   </dependency>

 

Pom file the complete contents of sub-project microservicecloud-provider-dept-hystrix-8001 are:

<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>
	<parent>
		<groupId>com.lss.springcloud</groupId>
		<artifactId>microservicecloud</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>microservicecloud-provider-dept-hystrix-8001</artifactId>
	<dependencies>

		<!-- hystrix -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix</artifactId>
		</dependency>




		<dependency><!-- 引入自己定义的api通用包,可以使用Dept部门Entity -->
			<groupId>com.lss.springcloud</groupId>
			<artifactId>microservicecloud-api</artifactId>
			<version>${project.version}</version>
		</dependency>

		<!-- 将微服务provider侧注册进eureka,注意,没有-server,说明是client端 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
		</dependency>

		<!-- actuator监控信息完善 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>



		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jetty</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
		</dependency>
		<!-- 修改后立即生效,热部署 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>springloaded</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>












		<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-core -->
		<dependency>
			<groupId>com.amazonaws</groupId>
			<artifactId>aws-java-sdk-core</artifactId>
			<version>1.11.125</version>
		</dependency>

		<dependency>
			<groupId>com.amazonaws</groupId>
			<artifactId>aws-java-sdk-autoscaling</artifactId>
			<version>1.11.125</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-bom -->
		<dependency>
			<groupId>com.amazonaws</groupId>
			<artifactId>aws-java-sdk-bom</artifactId>
			<version>1.11.125</version>
			<type>pom</type>
		</dependency>

		<dependency>
			<groupId>com.amazonaws</groupId>
			<artifactId>aws-java-sdk-ec2</artifactId>
			<version>1.11.125</version>
		</dependency>
		<!-- <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-pom</artifactId> 
			<version>1.11.125</version> </dependency> -->
		<dependency>
			<groupId>com.amazonaws</groupId>
			<artifactId>aws-java-sdk-sts</artifactId>
			<version>1.11.125</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.jdom/jdom2 -->
		<dependency>
			<groupId>org.jdom</groupId>
			<artifactId>jdom2</artifactId>
			<version>2.0.6</version>
		</dependency>









		<dependency>
			<groupId>org.apache.maven.shared</groupId>
			<artifactId>maven-dependency-tree</artifactId>
			<version>3.0.1</version>
		</dependency>
		<dependency>
			<groupId>org.vafer</groupId>
			<artifactId>jdependency</artifactId>
			<version>2.1.1</version>
		</dependency>
		<dependency>
			<groupId>org.ow2.asm</groupId>
			<artifactId>asm</artifactId>
			<version>7.0-beta</version>
		</dependency>
		<dependency>
			<groupId>org.ow2.asm</groupId>
			<artifactId>asm-analysis</artifactId>
			<version>7.0-beta</version>
		</dependency>
		<dependency>
			<groupId>org.ow2.asm</groupId>
			<artifactId>asm-tree</artifactId>
			<version>7.0-beta</version>
		</dependency>
		<dependency>
			<groupId>org.ow2.asm</groupId>
			<artifactId>asm-commons</artifactId>
			<version>7.0-beta</version>
		</dependency>
		<dependency>
			<groupId>org.ow2.asm</groupId>
			<artifactId>asm-util</artifactId>
			<version>7.0-beta</version>
		</dependency>







		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-loader-tools</artifactId>
			<version>2.2.4.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.3.13.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.apache.maven.shared</groupId>
			<artifactId>maven-shared-utils</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.9</version>
		</dependency>
		<dependency>
			<groupId>org.apache.maven</groupId>
			<artifactId>maven-core</artifactId>
			<version>3.3.9</version>
		</dependency>
		<dependency>
			<groupId>org.apache.maven</groupId>
			<artifactId>maven-repository-metadata</artifactId>
			<version>3.3.9</version>
		</dependency>
		<dependency>
			<groupId>org.eclipse.aether</groupId>
			<artifactId>aether-util</artifactId>
			<version>1.0.2.v20150114</version>
		</dependency>
		<dependency>
			<groupId>com.google.inject</groupId>
			<artifactId>guice</artifactId>
			<version>4.0</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.plexus</groupId>
			<artifactId>plexus-archiver</artifactId>
			<version>3.7.0</version>
		</dependency>
		<dependency>
			<groupId>org.ow2.asm</groupId>
			<artifactId>asm-commons</artifactId>
			<version>7.0</version>
		</dependency>
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>19.0</version>
		</dependency>


	</dependencies>
	<!-- <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> 
		<version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> 
		</configuration> </plugin> <plugin> <artifactId> maven-assembly-plugin </artifactId> 
		<configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> 
		</descriptorRefs> <archive> <manifest> <mainClass>com.lss.springcloud.EurekaServer7001_App</mainClass> 
		</manifest> </archive> </configuration> <executions> <execution> <id>make-assembly</id> 
		<phase>package</phase> <goals> <goal>single</goal> </goals> </execution> 
		</executions> </plugin> </plugins> </build> -->

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<executions>
					<execution>
						<goals>
							<goal>repackage</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>




</project>

 

And then update it.

 

 

 

The third step: yml file modification sub-project microservicecloud-provider-dept-hystrix-8001's.

Yml modify the contents of the file sub-project microservicecloud-provider-dept-hystrix-8001 are:

eureka:
  client: #客户端注册进eureka服务列表内
    service-url: 
      defaultZone: http://192.168.10.109:7001/eureka/,http://192.168.10.110:7002/eureka/,http://192.168.10.111:7003/eureka/
  instance:
    instance-id: microservicecloud-dept8001-hystrix   #自定义服务名称信息,此处需要修改因为不能重名
    prefer-ip-address: true     #访问路径可以显示IP地址

 

 

The complete contents of the sub-project microservicecloud-provider-dept-hystrix-8001's yml file is:

server:
  port: 8001
  
mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml  #mybatis所在路径
  type-aliases-package: com.lss.springcloud.entities #entity别名类
  mapper-locations:
  - classpath:mybatis/mapper/**/*.xml #mapper映射文件
    
spring:
   application:
    name: microservicecloud-dept 
   datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: org.gjt.mm.mysql.Driver
    url: jdbc:mysql://192.168.10.223:3306/cloudDB01
    username: root
    password: 数据库密码
    dbcp2:
      min-idle: 5
      initial-size: 5
      max-total: 5
      max-wait-millis: 200
      
eureka:
  client: #客户端注册进eureka服务列表内
    service-url: 
      defaultZone: http://192.168.10.109:7001/eureka/,http://192.168.10.110:7002/eureka/,http://192.168.10.111:7003/eureka/
  instance:
    instance-id: microservicecloud-dept8001-hystrix   #自定义服务名称信息
    prefer-ip-address: true     #访问路径可以显示IP地址
      
info:
  app.name: lss-microservicecloud
  company.name: www.lss.com
  build.artifactId: $project.artifactId$
  build.version: $project.version$
      
      
      
 

 

Step Four: Modify DeptController. How to deal with the @HystrixCommand reported abnormal. Once the call to service method fails with an error message, it will automatically call the specified method invocation good fallbackMethod class @HystrixCommand marked.

DeptController.java的修改内容是:

 @RequestMapping(value="/dept/get/{id}",method=RequestMethod.GET)
 @HystrixCommand(fallbackMethod = "processHystrix_Get")
  public Dept get(@PathVariable("id") Long id)
  {
   Dept dept =  this.service.get(id);
   if(null == dept)
   {
     throw new RuntimeException("该ID:"+id+"没有没有对应的信息");
   }
   return dept;
  }
  
  public Dept processHystrix_Get(@PathVariable("id") Long id)
  {
   return new Dept().setDeptno(id)
           .setDname("该ID:"+id+"没有没有对应的信息,null--@HystrixCommand")
           .setDb_source("no this database in MySQL");
  }

 

 

DeptController.java的完整内容是:

package com.lss.springcloud.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.lss.springcloud.entities.Dept;
import com.lss.springcloud.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@RestController
public class DeptController {

	@Autowired
	private DeptService service;

	@Autowired
	private DiscoveryClient client;

	@RequestMapping(value = "/dept/add", method = RequestMethod.POST)
	public boolean add(@RequestBody Dept dept) {
		return service.add(dept);
	}

	@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
	@HystrixCommand(fallbackMethod = "processHystrix_Get")
	public Dept get(@PathVariable("id") Long id) {
		Dept dept = this.service.get(id);
		if (null == dept) {
			throw new RuntimeException("该ID:" + id + "没有没有对应的信息");
		}
		return dept;
	}

	public Dept processHystrix_Get(@PathVariable("id") Long id) {
		return new Dept().setDeptno(id).setDname("该ID:" + id + "没有没有对应的信息,null--@HystrixCommand")
				.setDb_source("no this database in MySQL");
	}

	@RequestMapping(value = "/dept/list", method = RequestMethod.GET)
	public List<Dept> list() {
		return service.list();
	}

	@RequestMapping(value = "/dept/discovery", method = RequestMethod.GET)
	public Object discovery() {
		// 盘点eureka里面的微服务有哪些。
		List<String> list = client.getServices();
		System.out.println("**********" + list);

		List<ServiceInstance> srvList = client.getInstances("MICROSERVICECLOUD-DEPT");
		for (ServiceInstance element : srvList) {
			System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
					+ element.getUri());
		}
		return this.client;
	}

}

 

 

 

@HystrixCommand报异常后如何处理

 

 

第五步:修改主启动类DeptProvider8001_Hystrix_App并添加新注解@EnableCircuitBreaker。

 

 

 

 

 

 

 

DeptProvider8001_Hystrix_App.java的修改内容是:

@EnableCircuitBreaker//对hystrixR熔断机制的支持
public class DeptProvider8001_Hystrix_App {

 

 

 

DeptProvider8001_Hystrix_App.java的完整内容是:

package com.lss.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient //本服务启动后会自动注册进eureka服务中
@EnableDiscoveryClient//服务发现
@EnableCircuitBreaker//对hystrixR熔断机制的支持
public class DeptProvider8001_Hystrix_App {

	public static void main(String[] args) {
		SpringApplication.run(DeptProvider8001_Hystrix_App.class, args);
	}

}

 

 

 

第六步:测试

启动三个eureka,再启动主启动类DeptProvider8001_Hystrix_App(hystrix是服务提供者方),再启动Consumer启动microservicecloud-consumer-dept-80

http://192.168.10.115:83/consumer/dept/get/112

发布了155 篇原创文章 · 获赞 1 · 访问量 1万+

Guess you like

Origin blog.csdn.net/lbh19630726/article/details/104195272