美文网首页
SpringCloud 熔断器+feign

SpringCloud 熔断器+feign

作者: 楚长铭 | 来源:发表于2020-03-12 18:59 被阅读0次

依赖

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-hystrix'
    implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

配置

server:
  port: 3001
spring:
  application:
    name: hystrix-project
eureka:
  client:
    service-url:
      defaultZone: http://localhost:2000/eureka/


feign:
  httpclient:
    enabled: true
    #请求连接超时时间(毫秒)
    connection-timeout: 3000
  #启用okHttp
  okhttp:
    enabled: true
  #启用熔断器
  hystrix:
    enabled: true

  • feign的使用需要通过注册中心以接口形式调用其他服务的接口
  • feign要使用熔断器需要在配置文件中开启

主要注解

@EnableCircuitBreaker//熔断降级注解
@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class HystrixProjectApplication {

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

}
  • @EnableCircuitBreaker开启本服务熔断注解
  • @EnableFeignClients开启feign功能

feign的使用和熔断

@FeignClient(name = "test-project", fallbackFactory = TestProjectFallBackFactory.class)
public interface TestProjectFeignClient {

    @GetMapping("/")
    String test();

}
  • 定义接口添加注解@FeignClient;其中name属性是其他服务注册在注册中心的名字,可以在spring.application.name配置自定义
  • 其中的test方法就是test-project这个服务中的接口,在需要的地方注入调用即可
 @Autowired
private TestProjectFeignClient feignClient;

@GetMapping("/")
public String test() {
        return feignClient.test();
    }
  • fallbackFactory指定的是熔断之后执行的类,可以是使用fallback和FallbackFactory,建议使用FallbackFactory因为可以捕捉到异常信息
@Slf4j
@Component
public class TestProjectFallBackFactory implements FallbackFactory<TestProjectFeignClient> {


    @Override
    public TestProjectFeignClient create(Throwable cause) {

        log.info("查看错误信息:{}", cause);

        return new TestProjectFeignClient() {
            @Override
            public String test() {
                return "这是熔断之后返回的信息";
            }
        };


    }

}
  • 在这类自定义熔断之后的返回信息即可
  • 这种情况的熔断是服务之间的熔断

本服务内的熔断

    @GetMapping("/hello")
    @HystrixCommand(fallbackMethod = "noHello")
    public String hello() throws InterruptedException {

        Thread.sleep(10000);

        return "hello world";
    }

    public String noHello() {
        return "莫得感情";
    }
  • 在使用了@HystrixCommand注解可以定义某个方法级别的熔断,hello方法出现异常则会调用noHello方法,也可以传入参数但是参数名和位置必须完全一致

相关文章

网友评论

      本文标题:SpringCloud 熔断器+feign

      本文链接:https://www.haomeiwen.com/subject/xtshjhtx.html