SpringCloud 熔断器+feign

2020-03-12  本文已影响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


主要注解

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

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

}

feign的使用和熔断

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

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

}
 @Autowired
private TestProjectFeignClient feignClient;

@GetMapping("/")
public String test() {
        return feignClient.test();
    }
@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 "莫得感情";
    }
上一篇 下一篇

猜你喜欢

热点阅读