SpringCloud 之Hystrix 断路器/熔断器

简介:

                Hystrix 是一个用于处理分布式系统的延迟容错的开源库,在分布式系统里,许多依赖不可避免的会调用失败,比如超时,异常等,Hystrix能够保证在一个依赖关系出问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式的弹性

下图很好的解释了为什么有Hystrix的产生:

                 微服务长时间没有响应或者超时了 ,在服务于服务之间调用不恰当  ,会导致 系统瘫痪 ,挂起或者死机 这就叫做‘雪崩’

 雪崩:

 上代码:

 1.Hystrix  服务熔断:

 “断路器”本身是一种开关装置,当某个服务单元发生故障之后。通过断路器的故障监控(类似熔断保险丝),向调用方返回一个符合预期的,可处理的备选响应(FallBack),而不是长时间的等待或者抛出调用方无法处理的异常。这就保证了服务调用方的线程不会被长时间不必要的占用,从而避免了故障分布式系统的蔓延乃至“雪崩”。

yml文件:

server:
  port: 8001
  
mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml        # mybatis配置文件所在路径
  type-aliases-package: com.atguigu.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              # mysql驱动包
    url: jdbc:mysql://localhost:3306/cloudDB01            # 数据库名称
    username: root
    password: 123
    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: microservicecloud-dept8001
    prefer-ip-address: true     #访问路径可以显示IP地址     
 
info: 
  app.name: atguigu-microservicecloud
  company.name: www.atguigu.com
  build.artifactId: $project.artifactId$
  build.version: $project.version$

 controller层:

package com.atguigu.springcloud.controller;

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.atguigu.springcloud.entities.Dept;
import com.atguigu.springcloud.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@RestController
public class DeptController
{
	@Autowired
	private DeptService service = null;

	@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
	//一旦调用服务方法失败并抛出了错误信息后,会自动调用@HystrixCommand标注好的fallbackMethod调用类中的指定方法
	@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 null;
//		return new Dept().setDeptno(id).setDname("该ID:" + id + "没有没有对应的信息,null--@HystrixCommand")
//				.setDb_source("no this database in MySQL");
	}
}

启动类:

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

 2. Hystrix  服务降级:

服务熔断是对一个方法进行的处理 这样(高耦合)耦合性太高了 , 容易方法膨胀  。

扫描二维码关注公众号,回复: 5677166 查看本文章

那么就有对接口上熔断处理  这样就解耦了

业务方法与异常处理不要在一块 还是要干干净净业务逻辑层

  服务降级是:整体资源快不够用了,会先将一些服务关掉,度过难关之后,再回来开启

降级处理是在客户端实现的,与服务端没有关系

实现解耦: 

在任意一个包中添加一个类实现 FallbackFactory<DeptClientService>  DeptClientService就是你的接口类

package com.atguigu.springcloud.service;

import java.util.List;

import org.springframework.stereotype.Component;

import com.atguigu.springcloud.entities.Dept;

import feign.hystrix.FallbackFactory;

@Component // 不要忘记添加,不要忘记添加
public class DeptClientServiceFallbackFactory implements FallbackFactory<DeptClientService>
{
	@Override
	public DeptClientService create(Throwable throwable)
	{
		return new DeptClientService() {
			@Override
			public Dept get(long id)
			{
				return null;
//				return new Dept().setDeptno(id).setDname("该ID:" + id + "没有没有对应的信息,Consumer客户端提供的降级信息,此刻服务Provider已经关闭")
//						.setDb_source("no this database in MySQL");
			}

		};
	}
}

 不要忘记在你借口里添加  fallbackFactory=DeptClientServiceFallbackFactory.class

新建

一个实现了FallbackFactory接口的类DeptClientServiceFallbackFactory
 * @author zzyy
 * @date 2018年4月21日
 */
//@FeignClient(value = "MICROSERVICECLOUD-DEPT")
@FeignClient(value = "MICROSERVICECLOUD-DEPT",fallbackFactory=DeptClientServiceFallbackFactory.class)
public interface DeptClientService
{
	@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
	public Dept get(@PathVariable("id") long id);
}

因为是在Feign中调用接口 所以不要忘记添加 开启Hystrix

一旦我们关闭一个微服务那么 这个服务端就down了

  我们做了服务降级处理,让客户端在服务端不可用时也会获得提示信息而不会挂起耗死服务器

也就是说 访问一个服务的时候 访问不了 那么你会获得提示信息 那么你就不会一直访问这个服务 相当于这个服务就降级了

起到了对我们服务器的保护和友好的提示

总结:

猜你喜欢

转载自blog.csdn.net/qq_43224049/article/details/88779778