SpringCloud 中Hystrix的基本使用

导入依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>2.2.7.RELEASE</version>
</dependency>

RestTemplate整合

  1. 启动类添加注解@EnableCircuitBreaker

    @SpringBootApplication
    //旧版本
    //@EnableCircuitBreaker
    //新版本
    @EnableHystrix
    public class ClientdemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(ClientdemoApplication.class, args);
        }
    
    }
    
  2. 使用注解引进调用失败执行的方法

    @HystrixCommand(fallbackMethod = "service5Fail")
    public Object service5() {
        String url2 = "http://eurekaserve/shello";
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url2, String.class);
        System.out.println(forEntity.getBody());
        return "service5: " + forEntity.getBody();
    }
    
    public Object service5Fail(){
        return "service5Fail";
    }
    

Feign整合

开启Hystrix

//旧版本
feign.hystrix.enabled=true
//新版本
feign.circuitbreaker.enabled=true

方式一
实现API接口,重写方法

@Component
public class FeignTestImpl implements FeignTest {

    @Override
    public String shello() {
        return "shello is failed";
    }
}

注解配置fallback

@FeignClient(name = "eurekaserve",fallback = FeignTestImpl.class)
public interface FeignTest {

    @GetMapping(path = "/shello")
    String shello();

}

方式二
实现FallbackFactory接口,重写方法create(Throwable cause)

@Component
public class MyError implements FallbackFactory<FeignTest> {
    
    @Override
    public FeignTest create(Throwable cause) {
        return new FeignTest() {

            @Override
            public String shello() {
                if (cause instanceof Exception)
                    return "MyException";
                else
                    return "MyError";
            }

        };
    }
}

注解配置fallback

@FeignClient(name = "eurekaserve" ,fallbackFactory = MyError.class)
public interface FeignTest {

    @GetMapping(path = "/shello")
    String shello();

}
posted @ 2022-03-07 18:04  叕叕666  阅读(31)  评论(0)    收藏  举报