Hystrix

Hystrix实现容错

增加hystrix依赖
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
代码
    public List findFallback() {
        return Lists.newArrayList("fall back");
    }

    @HystrixCommand(fallbackMethod = "findFallback")
    @PostMapping("/movie")
    public List find() {
        return  restTemplate.postForObject("http://microservice-provider-user/api/user", null, List.class);
    }
启用Hystrix

启动类增加 @EnableHystrix 注解

测试

启动服务正常返回结果,关闭microservice-provider-user服务,再次调用返回[fall back]

feign使用Hystrix

SpringCloud默认已为Feign整合了Hystrix,下面实现Feign回退:

@Component
public class FeignClientFallBack implements UserFeignClient {
    @Override
    public String find() {
        return "fall back";
    }
}

@FeignClient(name = "microservice-provider-user"
        fallback = FeignClientFallBack.class)
public interface UserFeignClient {

    @PostMapping("/api/user")
    String find();

}

增加feign hystrix配置:

feign:
  hystrix:
    enabled: true
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。