1.熔断器
熔断器是为了防止“雪崩效应”的发生所提出的模型。
- 雪崩效应
下图为个独立服务之间的依赖关系,假设服务A出故障,不可使用,随着时间推移,服务A,B,C,D都会不可用,使得系统瘫痪。
2.项目现状
一个注册中心(registry),服务提供微服务(provider),消费者(ribbon),消费者(feign)
3.Ribbon项目
- POM文件中添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
- 启动类添加注解:@EnableHystrix
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class RibbonApplication {
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class, args);
}
@Bean
@LoadBalanced //Ribbon具有负载均衡的功能,添加该注解表示开启
RestTemplate restTemplate() {
return new RestTemplate();
}
}
- 对controller类进行修改
@RestController
public class TestController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("hello")
@HystrixCommand(fallbackMethod = "helloError")
public String hello(){
String str = "端口8082正在被调用:";
return str+restTemplate.getForObject("http://SERVER-PROVIDER/hello",String.class);
}
public String helloError(){
return "抱歉,服务出错!";
}
}
- 正常结果
端口8082正在被调用:hello
- 熔断结果
抱歉,服务出错
4. Feign项目
- Feign自带Hystrix,D版本后默认为关闭,需要手动开启
feign:
hystrix:
enabled: true
- 修改Client
@FeignClient(value = "SERVER-PROVIDER",fallback = HelloError.class)
public interface HelloClient {
@GetMapping("hello")
String hello();
}
@Component
public class HelloError implements HelloClient{
public String hello(){
return "抱歉,服务故障!";
}
}
- 正常结果
8083端口正在被调用:hello
- 熔断结果
8083端口正在被调用:抱歉,服务故障!