它的作用是:当某个业务发生故障,通过断路器监控,向一个调用方返回一个错误相应,而不是长时间等待,避免了故障在分布式系统中的蔓延。
- 服务熔断与降级
熔断机制是应对雪崩效应的一种保护机制,当某个微服务不可用或长时间不响应,会进行服务降级,进而熔断该节点微服务的调用,快速返回错误的响应信息,当微服务恢复正常后 恢复调用。
-
服务提供方熔断
- 新建服务端项目,jar包、配置同之前样例https://mp.csdn.net/console/editor/html/103808970
- 在启动类上开启hystrix
@EnableCircuitBreaker
- 建立正式方法及备用方法
@RequestMapping("/test")
@RestController
public class TestController {
@RequestMapping("/get/{id}")
@HystrixCommand(fallbackMethod = "getForBack")
public String get(@PathVariable("id") String id) {
System.out.println("服务端收到的id为:" + id);
if (id.equals("2")) {
throw new RuntimeException("报错");
}
return "服务端1";
}
public String getForBack(@PathVariable("id") String id) {
return "回调方法-服务端1";
}
}
- 将所有服务都启动。可以发现id为2的时候,走了备用方法
- 在上面样例上继续操作
- 在service,接口提供包里加一个类,TestService就是feigin接口
@Component
public class FallBackFactory implements FallbackFactory<TestService> {
@Override
public TestService create(Throwable throwable) {
return new TestService() {
@Override
public String get(String id) {
return "接口没有调通";
}
};
}
}
- 在接口上添加fallback
@FeignClient(name = "PRODUCT", configuration = FeignClientConfig.class, fallbackFactory = FallBackFactory.class)
public interface TestService {
@RequestMapping("/test/get/{id}")
public String get(@PathVariable("id") String id);
}
- 在消费端添加配置
feign:
hystrix:
enabled: true
- 结束
服务提供方关掉之后,