ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# Hystrix简介 Hystrix是netflix的一个开源项目,它能够在依赖服务失效的情况下,通过隔离系统依赖服务的方式,防止服务级联失败;同时Hystrix提供失败回滚机制,使系统能够更快的从异常中恢复。spring-cloud-netflix-hystrix 对Hystrix进行了封装和适配,为微服务间调用提供强有力的容错机制 ***** ## 1、RestTemplate与Hystrix 首先添加eureka-client和hystrix的相关依赖; ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> ``` 通过@EnableCircuitBreaker注解开启Hystrix,同时注入可以负载均衡的RestTemplate,代码如下: ``` @SpringBootApplication @EnableCircuitBreaker // 开启Hystrix public class HystrixApplication{ @Bean @LoadBalanced RestTemplate restTemplate(){ return new RestTemplate(); } } ``` 在调用的方法上添加注解@HystrixCommand,方式如下: ``` @Service public class Service{ @Autowired RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "getFail") // 指定调用失败的方法 public String getName(){ retrun restTemplate.getForEntity(url); } public String getFail(){ retrun "error"; } } ``` ## 2、OpenFeign与Hystrix OpenFeign是自带Hystrix,默认没有打开,需要在application.yml中添加配置开启: ``` feign: hystrix: enabled: true # hystrix配置 hystrix: metrics: enabled: true # 默认的超时时间设置 单位为毫秒 hystrix: metrics: polling-interval-ms: 2000 ``` 启动类添加注解@EnableFeignClients @EnableCircuitBreaker 在调用service服务时,指定失败回滚类: ``` @FeignClient(value = "feign-service" ,fallback = ClientFallback.class) public interface Client { } // ClientFallback 类实现 Client public class ClientFallback implements Client { } ```