Hystrix(下),使用公共降级类

使用Hystrix熔断(下)

在一个分布式系统里,一个服务依赖多个服务,可能存在某个服务调用失败,

        比如超时、异常等,如何能够保证在一个依赖出问题的情况下,不会导致整体服务失败,

 

copy orderserverfeign项目,并更名为orderserverfeignhystrix

        在项目右键修改名称

        pom中修改artifactId为

        pom中修改name为

        修改包名称

        修改各种类名称增加hystrix

        在运行左侧的edit application中修改名称

        @RequestMapping("/api/v1/orderfeign")修改为@RequestMapping("/api/v1/orderfeignhystrix")

2、增加依赖到pom文件

     <dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>

</dependency>

3、启动类增加注解

        @EnableCircuitBreaker

        

        关注注解@SpringCloudApplication,包含以下注解

            @Target({ElementType.TYPE})

            @Retention(RetentionPolicy.RUNTIME)

            @Documented

            @Inherited

            @SpringBootApplication

            @EnableDiscoveryClient

            @EnableCircuitBreaker

4、ProductFeignHystrixService这个类下面要修改注解

        @FeignClient(name="PRODUCT-SERVICE")修改为

        @FeignClient(name="PRODUCT-SERVICE", fallback = ProductOrderHystrixFallback.class) 可以在这个类中找到各种需要熔断和降级的方法

5、增加一个fallback包,在其下增加一个类ProductOrderHystrixFallback,用于公共方法的熔断和降级,并继承productclient,加注解@Component,alt+insert 重写类findById

        @Override

        public String fingById(int id) {

            return null;

        }

 

至此两种熔断的方法使用上了

1、controller对应的类中增加@HystrixCommand(fallbackMethod = "saveOrderFail")

2、单独增加一个包,对所有服务类可以增加一个熔断或者降级后处理的方法

    增加一个fallback包,在其下增加一个类ProductOrderHystrixFallback,并继承productclient,加注解@Component,alt+insert 重写类findById

原文地址:https://www.cnblogs.com/programer-xinmu78/p/10540807.html