Fegin Hystrix не эффективен

Я попытался Feign настроить Hystrix. Введите 127.0.0.1:8100/test в адресную строку браузера. Независимо от того, настроен ли он с резервным или резервным заводом, результат подсказки: «com.netflix.client.ClientException: Балансировщик нагрузки не имеет доступного сервера для клиента: микросервис-поставщик-пользователь», это Объясните, что резервный вариант не работающий.

Контроллер


@Import(FeignClientsConfiguration.class)
@RestController
public class TestController {

    private UserFeignClient userFeignClient;

    private UserFeignClient adminFeignClient;

    @Autowired
    public TestController(Decoder decoder, Encoder encoder, Client client, Contract contract) {
        this.userFeignClient = Feign.builder().client(client).encoder(encoder)
                .decoder(decoder).contract(contract)
                .requestInterceptor(new BasicAuthRequestInterceptor("user", "user"))
                .target(UserFeignClient.class, "http://microservice-provider-user/");

        this.adminFeignClient = Feign.builder().client(client).encoder(encoder)
                .decoder(decoder).contract(contract)
                .requestInterceptor(new BasicAuthRequestInterceptor("admin", "admin"))
                .target(UserFeignClient.class, "http://microservice-provider-user/");
    }

    @GetMapping("/test")
    @ResponseBody
    public String test() {
        return userFeignClient.findById(123L);
    }

    @GetMapping("/testAdmin")
    @ResponseBody
    public String test2() {
        return adminFeignClient.findById(123L);
    }
}

Основной метод


@SpringBootApplication
@EnableFeignClients
@EnableHystrixDashboard
@EnableHystrix
@EnableCircuitBreaker
public class Demo2Application {

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

}

отступать

@Component
public class FeignClientFallback implements UserFeignClient{
    @Override
    public String findById(Long id) {
        return "hello FeignClientFallback";
    }
}

градиент

plugins {
    id 'org.springframework.boot' version '2.1.3.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

ext {
    set('springCloudServicesVersion', '2.1.2.RELEASE')
    set('springCloudVersion', 'Greenwich.SR1')
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    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-netflix-hystrix-dashboard'
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-turbine'
    implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

dependencyManagement {
    imports {
        mavenBom "io.pivotal.spring.cloud:spring-cloud-services-dependencies:${springCloudServicesVersion}"
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

Притвориться клиентом

@FeignClient(name = "microservice-provider-user", fallback = FeignClientFallback.class)
public interface UserFeignClient {

    @GetMapping("/test2/{id}")
    String findById(@PathVariable("id") Long id);
}

приложение.yml

spring:
  application:
    name: microservice-custom
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/
    healthcheck:
      enabled: true
  instance:
    prefer-ip-address: true

server:
  port: 8100

feign:
  hystrix:
    enabled: true
  client:
    config:
      default:
        connectTimeout: 1000
        readTimeout: 1000
        loggerLevel: basic

hystrix:
  command:
    default:
      execution:
        isolation:
          strategy: SEMAPHORE

logging:
  level:
    com.lv.springCloudClient1.UserFeignClient: DEBUG

management:
  endpoints:
    web:
      exposure:
        include: '*'

Теоретически, если я отключу сервер «микросервис-поставщик-пользователь», я получу контент, возвращаемый резервным методом.


person lvqiang    schedule 28.03.2019    source источник
comment
Убедитесь, что на сервере eureka отображается служба с именем microservice-provider-user. Предоставьте полные журналы   -  person Barath    schedule 28.03.2019
comment
Страница сервера eureka отображает только MICROSERVICE-CUSTOMX n/a (1) (1) UP (1) - 192.168.2.31:microservice-customx:8100, потому что пользователь-поставщик-микросервиса был закрыт   -  person lvqiang    schedule 28.03.2019
comment
хорошо, вот почему выдает ошибку, попробуйте поднять ее и проверить, работает ли она.   -  person Barath    schedule 28.03.2019
comment
Но ожидаемый результат — это возвращаемое значение метода findById в классе FeignClientFallback. Теоретически я отключил службу microservice-provider-user. Возвращаемое значение не должно быть Load balancer does not have available server for client. Не так ли?   -  person lvqiang    schedule 28.03.2019
comment
Смущенный. Вы создали фиктивные клиенты вручную с помощью java DSL, что может быть причиной того, что совет не работает.   -  person Barath    schedule 28.03.2019
comment
Я пытался использовать @AutoWired для создания симуляции, без ручного, это работает. Я сам проверю следующую проблему, связанную с созданием фиктивных клиентов вручную. Спасибо! 谢谢。   -  person lvqiang    schedule 28.03.2019
comment
@Ivqiang прав. Чтобы получить автоматическую резервную обработку при использовании Spring, вам необходимо зарегистрировать FeignClients как Beans и внедрить их в свои классы обслуживания.   -  person Kevin Davis    schedule 20.05.2019


Ответы (1)



@Import(FeignClientsConfiguration.class)
@RestController
public class TestController {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private UserFeignClient adminFeignClient;

    @GetMapping("/test")
    @ResponseBody
    public String test() {
        return userFeignClient.findById(123L);
    }

    @GetMapping("/testAdmin")
    @ResponseBody
    public String test2() {
        return adminFeignClient.findById(123L);
    }
}

Я изменил предыдущий код контроллера на текущий. эффективен резервный метод Hystrix.

person lvqiang    schedule 28.03.2019