springcloud-feign的hystrix支持 springcloud-断路器hystrixs

关于hystrix的介绍,可以看我的上篇博客:springcloud-断路器hystrixs

本文主要介绍在feign中,如何使用hystrix

1、pom依赖

      <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
        <dependency>
            <!-- hystrix 断路器 -->
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>com.xwj</groupId>
            <artifactId>spring-cloud-core</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

2、入口开启feign和hystrix

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients // 开启feign
@EnableCircuitBreaker // 开启断路器
public class ConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }

}

3、在yml文件打开feign对hystrix的支持(关于hystrix的配置,本篇不做介绍)

feign:
  hystrix:
    enabled: true #打开feign对hystrix的支持

4、修改FeignClient,增加 fallback 参数,这是接口的降级回调类

@FeignClient(name = "service-provider", fallback = UserFallback.class)
public interface UserFeignClient {

    @GetMapping("/find/{id}")
    UserEntity findById(@PathVariable("id") Long id); // PathVariable必须得设置value

}

5、创建降级回调类UserFallback

/**
 * 错误回调类
 */
@Component
public class UserFallback implements UserFeignClient {

    @Override
    public UserEntity findById(Long id) {
        UserEntity user = new UserEntity();
        user.setId("1000");
        user.setAge(12);
        return user;
    }

}

猜你喜欢

转载自www.cnblogs.com/xuwenjin/p/9349737.html