참조 : 팡 지펭 열
소개 1. Hystrix
마이크로 서비스 아키텍쳐에서 서비스에 따른 서비스간에 서로 (RPC) 서비스를 호출 할 수있는 서비스들로 분할하고 RestTemplate + 척하기 리본을 이용하고 스프링이 클라우드를 호출 할 수있다. 가용성, 하나의 서비스들은 클러스터 구축을 보장하기 위해. 단일 서비스 문제가 스레드가 차단 될 것입니다이 서비스를 호출하기 위해 발생하는 경우 많은 수의 요청의 유입은, 서블릿 컨테이너 스레드 자원이 완료 소모 될 경우 자신의 이유로 네트워크 이유 또는 서비스가이 시간에, 가능한 100 %를 보장하지 않습니다 서비스의 마비의 결과. 서비스 및 서비스 실패 사이의 종속성이 확산됩니다 전체 마이크로 시스템이 재앙 심각한 결과를 서비스한다, 이것은 "눈사태"효과 서비스 장애입니다.
이 문제를 해결하기 위해 업계는 회로 차단기 모델을 제안 하였다.
컷 아웃 모드를 달성하기 위해 넷플릭스 Hystrix 오픈 소스 구성 요소는 구성 요소의 SpringCloud가 통합되었다. 마이크로 서비스 구조에서 요청이 필요 아래와 같이 여러 서비스가 매우 일반적인 호출 :
오류가 발생하면 깊은 서비스, 그것은 계단식 실패로 이어질 것입니다. 특정 서비스가 임계치에 도달에 대한 요구가없는 경우 (Hystric 5초 20 회) 회로 차단기가 열린다.
열린 차단 한 후, 실패 계단식 피하기 위해 사용될 수 있고, 대체 방법은 고정 된 값에 직접 반환 할 수있다.
이 문서는 건설이 첫 번째 기사에서 시작 엔지니어링의 기사를 기반으로, 유레카 서버 프로젝트를 시작, 프로젝트 시작 서비스 - 안녕하세요, 포트는 8762입니다.
2. 리본의 회로 차단기
코드 서비스 리본 혁신 프로젝트는, 첫째 pox.xml 파일에 의존하는 스프링 클라우드 스타터 넷플 릭스 - hystrix을 추가 시작 :
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
在程序的启动类ServiceRibbonApplication 加@EnableHystrix注解开启Hystrix:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication @EnableEurekaClient @EnableDiscoveryClient @EnableHystrix public class ServiceRibbonApplication { public static void main(String[] args) { SpringApplication.run( ServiceRibbonApplication.class, args ); } @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } }
改造HelloService类,在hiService方法上加上@HystrixCommand注解。该注解对该方法创建了熔断器的功能,并指定了fallbackMethod熔断方法,熔断方法直接返回了一个字符串,字符串为”hi,”+name+”,sorry,error!”,代码如下:
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class HelloService { @Autowired RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "hiError") public String hiService(String name) { return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class); } public String hiError(String name) { return "hi,"+name+",sorry,error!"; } }
启动:service-ribbon 工程,当我们访问http://localhost:8764/hi?name=zang,浏览器显示:
此时关闭 service-hi 工程,当我们再访问http://localhost:8764/hi?name=forezp,浏览器会显示:
这就说明当 service-hi 工程不可用的时候,service-ribbon调用 service-hi的API接口时,会执行快速失败,直接返回一组字符串,而不是等待响应超时,这很好的控制了容器的线程阻塞。
3. Feign中使用断路器
Feign是自带断路器的,在D版本的Spring Cloud之后,它没有默认打开。需要在配置文件中配置打开它,在配置文件加以下代码:
feign.hystrix.enabled: true
基于service-feign工程进行改造,只需要在FeignClient的SchedualServiceHi接口的注解中加上fallback的指定类就行了:
import com.zang.servicefeign.clients.fallback.SchedualServiceHiHystric; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @FeignClient(value = "service-hi",fallback = SchedualServiceHiHystric.class) public interface SchedualServiceHi { @RequestMapping(value = "/hi",method = RequestMethod.GET) String sayHiFromClientOne(@RequestParam(value = "name") 문자열 이름); }
다음과 같이, SchedualServiceHiHystric SchedualServiceHi 인터페이스를 구현해야하며 IOC의 용기에 주입 :
수입 com.zang.servicefeign.clients.SchedualServiceHi; 수입 org.springframework.stereotype.Component; @Component 공공 클래스 SchedualServiceHiHystric 구현 SchedualServiceHi는 { @Override 공공 문자열 sayHiFromClientOne (문자열 이름) { 반환 + "죄송합니다, 당신은 실패하는" 이름을; } }
시작 servcie - 체하다 프로젝트 브라우저에 http 열려면 : // localhost를 :? 8765 / 안녕하세요 이름 = ZANG, 주이 시간에 프로젝트가 시작되지 않는 서비스를-안녕하세요, 웹 페이지 표시 :
오픈 서비스 안녕하세요 엔지니어링, 다시 브라우저 표시 액세스 :
이 회로 차단기는 역할을하고 있음을 증명한다.