springcloud hystrix熔断机制

hystrixd的实现原理,基于线程隔离,再加上保护机制,才实现了熔断

进行feign调用时,假如被调用方出现了网络故障或全部节点都不可用,这个时候就造成了调用方线程堵塞,最终导致调用方的线程耗尽,导致调用方资源耗尽,从而影响到所有服务最终资源耗尽,都不可用,这就是服务雪崩的现象

解决服务雪崩:使用熔断器(断路器)对服务调用进行保护,使用hystrix,hystrix会自动检测每次feign调用的时长以及失败率,当达到阈值的时候,hystrix会自动断开feign调用,调用回滚类的回滚方法,进行快速响应,避免线程堵塞带来的资源耗尽问题

hystrix的断路器处于闭合 状态,断路之后,每隔5s尝试feign的远程地址,默认超时时间是1s

配置方式

1.导入包,在common中引入,然后服务 引入common即可

<!--用户使用hystrix熔断机制-->
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
           <version>2.0.3.RELEASE</version>
       </dependency>

启动类扫描rollback

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@MapperScan("com.oracle.shop.orders.mapper")
@EnableTransactionManagement //开启事务管理
@EnableFeignClients("com.oracle.shop.common.feign")//feign客户端扫描
@ComponentScan("com.oracle.shop") //扫描所有的,包括rollback
public class OrdersServer {

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


   @Bean   //实例化一个restTemplate 进行http调用
   @LoadBalanced
   public RestTemplate restTemplate(){
       return new RestTemplate();
  }
}

在配置文件中开启以及配置hystrix

#hystrix的配置
#开启hystrix
feign.hystrix.enabled=true
#设置超时时间
hystrix.command.HystrixCommandKey.execution.isolation.thread.timeoutInMilliseconds=3000
#指建立连接后从服务端读取到可用资源所用的时间
ribbon.ReadTimeout=3000

 

posted @ 2021-12-01 13:59  2333gyh  阅读(184)  评论(0编辑  收藏  举报