hystrix学习

hystrix是一个用于处理分布式系统延迟和容错的开源库,在系统中,如出现超时,异常等,hystrix能够保证三个依赖出问题的情况下,不会导致整个服务失败,避免级联故障,提高了分布式的弹性。

加入依赖:

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>

HystrixCommand(fallbackMethod = "失败后调用的方法")

@Autowired
    private TestClientService testServcie;

    @RequestMapping(value = "person/get/{id}",method = RequestMethod.GET)
    @HystrixCommand(fallbackMethod="error_get")
    public Person get(@PathVariable("id")Long id){

    }
 

   public Person error_get(@PathVariable("id")Long id){
          return "信息"
   }

启动类上要加@EnableCircuitBreaker //hystrix熔断机制的支持

 


 

服务降级:

  使用HystrixCommand有太多冗余,所以我们要在接口上实现

@Component
public class TestClientServiceFallbackFactory implements FallbackFactory<TestClientService> {
    @Override
    public TestClientService create(Throwable throwable) {
        return new TestClientService() {
            @Override
            public Person get(Person person) {
                return "错误信息";
            }
        };
    }
}
TestClientService:
@FeignClient(value = "MICROSERVICECLOUD",fallbackFactory = TestClientServiceFallbackFactory.class)
public interface TestClientService {

    @RequestMapping(value = "/person/get/{id}")
    public Person get(@PathVariable("id") Long id);

}

feign的项目里要加上

feign:
  hystrix:
    enabled: true

HystrixDashboard

添加注解

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
        </dependency>

在启动类上加

@EnableHystrixDashboard

 

posted on 2018-08-17 14:53  Java挖掘机  阅读(137)  评论(0编辑  收藏  举报

导航