Hystrix breaker spring cloud of learning (e)

Hystrix breaker Learning (Five)

table of Contents

Outline

Distributed system problems faced by

What is Hystrix

Hystrix role

Outline

 

Distributed system problems faced by

Complex distributed application architecture dozens of dependencies Each dependency at some point will inevitably fail .

Server downtime, how to do;

 

Avalanche Service

When calls between a plurality of micro services, assuming that the 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.

What is Hystrix

Hystrix is a distributed system for processing delays and fault-tolerant open source library, in a distributed system, 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), returns to the caller a line with expectations, the response may be processed alternatively (FallBack) instead of waiting for a long time or throw an exception caller can not handle, thus ensuring the caller to the service thread it will not be long, unnecessarily occupied, so as to avoid the spread of the fault in the distributed system, and even avalanche.

Official website information   https://github.com/Netflix/Hystrix/wiki/How-To-Use

Hystrix role

Service fuse

Service fuse

       Usually caused by a service failure or abnormal, similar to the real world, "Fuse", when an abnormal condition is triggered, directly fuse the entire service, not always wait for this service timeout.

A micro-fuse mechanism is to deal with 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.

Hystrix breaker

  1. Maven ---- GAV coordinates
  2. The new annotation label corresponding technical component
    1. @EnableXXX
    2. @HystrixCommand

 

Returns to the caller a line with expectations, can handle alternative responses (FallBack), rather than the long wait or throw caller unhandled exception
will downgrade the service, and then blown call the micro-node service, fast return to the "wrong" response information.

 

参考: springcloud-model-provider-dept-8001

New sub-module project springcloud-model-provider-dept-hystrix-8001

First, the maven --- GAV coordinates

<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.jiangjy.springcloud</groupId>
    <artifactId>springcloud-model</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>springcloud-model-provider-dept-hystrix-8001</artifactId>
<dependencies>
		<!-- 引入自己定义的api通用包,可以使用Dept部门pojo 
		<version>${project.version}</version>灵活的版本
		-->
		<dependency>
			<groupId>com.jiangjy.springcloud</groupId>
			<artifactId>springcloud-model-api</artifactId>
			<version>${project.version}</version>
		</dependency>
		<!-- 测试 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<!-- mysql驱动包 -->
		<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>
		<!-- mybatis-spring整合 -->
		<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>
		
		<!-- Euraka客户端  将微服务provider侧注册进eureka -->
		<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>
  		
  		 <!--  hystrix 相关 -->
  		 <dependency>
  		 	<groupId>org.springframework.cloud</groupId>
  		 	<artifactId>spring-cloud-starter-hystrix</artifactId>
  		 </dependency>  		
	</dependencies>

</project>

Application.yml file configuration

server:
  port: 8001  #访问的端口号

#mybatis整合
mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml   #mybatis配置文件所在路径
  type-aliases-package: com.jiangjy.springcloud.pojo   #所有pojo别名类所在包
  mapper-locations:
  - classpath:mybatis/mappers/*.xml    #mapper映射文件
  
#spring整合
spring:
  application:
    name: springcloud-model-dept   #项目对外暴露的访问名称
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型    
    driver-class-name: com.mysql.jdbc.Driver                # mysql驱动包 com.mysql.jdbc.Driver的前身是org.gjt.mm.mysql.Driver,
                                                            #  现在主要用com.mysql.jdbc.Driver,但为了保持兼容性保留了org.gjt.mm.mysql.Driver这个路径的引用。
    url: jdbc:mysql://localhost:3306/springcloud01              # 数据库名称
    username: root
    password: root
    dbcp2:
      min-idle: 5                                           # 数据库连接池的最小维持连接数
      initial-size: 5                                       # 初始化连接数
      max-total: 5                                          # 最大连接数
      max-wait-millis: 200                                  # 等待连接获取的最大超时时间    

eureka:
  client:   #客户端注册进eureka服务列表内
    service-url:
#单机版      defaultZone: http://localhost:7001/eureka/
        defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  instance: 
    instance-id: springcloud-dept8001-hystrix    #自定义服务名称信息
    prefer-ip-address: true   #访问路径可以显示IP地址
    
info:
  app.name: jiangjy-springcloud
  company.name: www.jiangjy.com
  build.artifactId: $project.artifactId$ 
  build.version: $project.version$   

Service Provider (maven) --- configuration file (yml) --- coding

 

Control layer class DeptController:

How @HystrixCommand newspaper after exception handling:

Once the call to service method fails with an error message, it will automatically call the specified method @HystrixCommand annotation good fallbackMethod call class

package com.jiangjy.springcloud.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.jiangjy.springcloud.pojo.Dept;
import com.jiangjy.springcloud.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@RestController
public class DeptController {

	@Autowired
	private DeptService deptService;
	
	
	@RequestMapping(value = "/dept/getById/{id}",method = RequestMethod.GET)
	@HystrixCommand(fallbackMethod = "processHystrix_GetById")//一旦调用服务方法失败并抛出了错误信息后,会自动调用@HystrixCommand标注好的fallbackMethod调用类中的指定方法
	public Dept getById(@PathVariable("id") Long id) {
		
		Dept dept = deptService.getById(id);
		
		if (dept == null) {
			throw new RuntimeException("该id:" + id + "没有对应的信息");
		}
		
		return dept;
	}
	
	public Dept processHystrix_GetById(@PathVariable("id") Long id) {
		
		return new Dept().setDeptno(id).setDname("该id:" + id + "没有对应的信息   " + " null---@HystrixCommand")
				.setDb_source("no this DataBase in MySQL");
	}
	
}

Modify the master boot DeptProvider8001_Hystrix_App class and add a new comment @EnableCircuitBreaker

package com.jiangjy.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);
	}
}

 

Test: Start order

First start three Eureka Service

Sign up to start the main class DeptProvider8001_Hystrix_App Eureka

Consumer启动springcloud-model-consumer-dept-80

http://localhost/consumer/dept/getById/18

Test: Normal No. 1 some data

Test: 18 results with no data

 

 

Service downgraded

What is service degradation:

Overall resources fast enough, some reluctantly turn off the service, to be ride out the storm, and then turn back.

The so-called demotion, is generally considered the whole load. When the fuse is a service, the server will no longer be called, this time a client can prepare their own local fallback callback returns a default value.

In doing so, although the reduction in the level, but whatever the outcome is available, than the direct hang stronger.
Service degradation process is done on the client side to achieve, nothing to do with the server

 

Modify springcloud-model-api project

According to already have achieved a new interface to DeptClientService

Class interface DeptClientServiceFallbackFactory FallbackFactory

Do not forget to add top class @Component notes, this is a pit! ! !

package com.jiangjy.springcloud.service;

import java.util.List;

import org.springframework.stereotype.Component;

import com.jiangjy.springcloud.pojo.Dept;

import feign.hystrix.FallbackFactory;

@Component  //类之上千万不要忘记新增@Component注解,这是一个大坑!!!  
public class DeptClientServiceFallbackFactory  implements FallbackFactory<DeptClientService>{

	@Override
	public DeptClientService create(Throwable cause) {
		// TODO Auto-generated method stub
		return new DeptClientService() {
			
			@Override
			public Dept getById(Long id) {
				return new Dept().setDeptno(id).setDname("该id:" + id + "没有没有对应的信息,Consumer客户端提供的降级信息,此刻服务Provider已经关闭")
						.setDb_source("no this DataBase in MySQL");
			}
			
			@Override
			public List<Dept> getAll() {
				// TODO Auto-generated method stub
				return null;
			}
			
			@Override
			public boolean add(Dept dept) {
				// TODO Auto-generated method stub
				return false;
			}
		};
	}

}

 

Modify springcloud-model-api project, DeptClientService add the interface fallbackFactory property values ​​in the comment @FeignClient

package com.jiangjy.springcloud.service;

import java.util.List;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jiangjy.springcloud.pojo.Dept;

//@FeignClient(value = "SPRINGCLOUD-MODEL-DEPT")  //面向服务中的注解+接口
@FeignClient(value = "SPRINGCLOUD-MODEL-DEPT",fallbackFactory=DeptClientServiceFallbackFactory.class)
public interface DeptClientService {

	@RequestMapping(value = "/dept/getAll",method = RequestMethod.GET)
	public List<Dept> getAll();
	
	@RequestMapping(value = "/dept/getById/{id}", method = RequestMethod.GET)
	public Dept getById(@PathVariable("id") Long id);
	
	@RequestMapping(value = "/dept/add",method = RequestMethod.POST)
	public boolean add(Dept dept);
	
}

 

Before starting, first springcloud-model-api project  

mvn clean install

springcloud-model-consumer-dept-feign engineering change YML

server:
  port: 80

feign: 
  hystrix: 
    enabled: true

eureka:
  client: 
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
      

Test: Start order

First start three eureka Service

Micro Services springcloud-provider-dept-8001 start

springcloud-consumer-dept-feign启动

 

Normal access test: HTTP: // localhost / Consumer / the dept / getById / 1

Deliberately closed micro-services springcloud-provider-dept-8001

The client's own call Tip: HTTP: // localhost / Consumer / the dept / getById / 1

At this point the server provider has been down, but we have done a service degradation process, so that the client will get prompt information when the server is unavailable and does not suspend the consumption of dead server


 

 

Service Monitoring hystrixDashboard

Overview:

         In addition to calling isolation dependent services, Hystrix also provides a quasi- real-time call monitoring (Hystrix Dashboard) , Hystrix will continue to record execution information for all by Hystrix initiated the request, and presented to the user in the form of statistical reports and graphs , including how many successful execution of the request number, the number of failures per second and so on. Netflix realized the monitoring of these indicators by hystrix-metrics-event-stream projects. Spring Cloud also provides integrated Hystrix Dashboard, and monitoring content into visual interface.

 

 

step

New construction springcloud-model-consumer-hystrix-dashboard

pom.xml file GAV coordinates

<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.jiangjy.springcloud</groupId>
    <artifactId>springcloud-model</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>springcloud-model-consumer-hystrix-dashboard</artifactId>
  
   <dependencies>
		<dependency><!-- 自己定义的api -->
			<groupId>com.jiangjy.springcloud</groupId>
			<artifactId>springcloud-model-api</artifactId>
			<version>${project.version}</version>
		</dependency>
		<!-- feign相关jar -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-feign</artifactId>
		</dependency>
		
		<!-- Ribbon相关,详情见文档 -->
		<!-- eureka客户端 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-ribbon</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		
		<!-- hystrix和 hystrix-dashboard相关-->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
		</dependency>
		
		<!-- 修改后立即生效,热部署 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>springloaded</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>
		
	</dependencies>
</project>

application.yml file

server:
  port: 9001

+ New master boot class notes @EnableHystrixDashboard

package com.jiangjy.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;

@SpringBootApplication
@EnableHystrixDashboard
public class DeptConsumer_DashBoard_App {

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

 

First, all the services provided micro Provider class (8001/8002/8003) will need to be monitored depend on configuration

See all the provider sub-module project pom.xml file

Whether to add monitoring by the actuator

二、启动springcloud-model-consumer-hystrix-dashboard该微服务监控消费端(示例)

http://localhost:9001/hystrix

三、启动3个eureka集群

四、启动springcloud-model-provider-dept-hystrix-8001

       http://localhost:8001/dept/getById/1

http://localhost:8001/hystrix.stream

五、启动的相关微服务工程

六、监控测试

       多次刷新http://localhost:8001/dept/getById/1

       观察监控窗口:

                     填写监控地址:  9001监控8001

1:Delay:该参数用来控制服务器上轮询监控信息的延迟时间,默认为2000毫秒,可以通过配置该属性来降低客户端的网络和CPU消耗。

 

2:Title:该参数对应了头部标题Hystrix Stream之后的内容,默认会使用具体监控实例的URL,可以通过配置该信息来展示更合适的标题。 

监控结果

 

如何看?7色  

1圈

实心圆:共有两种含义。它通过颜色的变化代表了实例的健康程度,它的健康度从绿色<黄色<橙色<红色递减。

该实心圆除了颜色的变化之外,它的大小也会根据实例的请求流量发生变化,流量越大该实心圆就越大。所以通过该实心圆的展示,就可以在大量的实例中快速的发现故障实例和高压力实例。

1线

       曲线:用来记录2分钟内流量的相对变化,可以通过它来观察到流量的上升和下降趋势。

 整图说明

搞懂一个才能看动复杂的

 

 

 

 

 

服务限流

接近实时的监控

 


发布了17 篇原创文章 · 获赞 42 · 访问量 9565

Guess you like

Origin blog.csdn.net/jiangjiaoyong/article/details/102916605