Отчет Spring Cloud Feign 404

Я использую Eureka для регистрации службы и использую Feign для обнаружения служб, но если я не добавлю параметры URL, система сообщит об исключении 404. И мой идентификатор кода ниже не работает:

@FeignClient(name = "CRAWLER-SERVICE")

И ниже работает код:

@FeignClient(name = "crawler-service", url = "http://192.168.199.229:8091/crawler")

Трассировка стека:

feign.FeignException: status 404 reading CrawlerServiceApi#queryAllConditions(String,String)
    at feign.FeignException.errorStatus(FeignException.java:62) ~[feign-core-9.5.0.jar:na]
    at feign.codec.ErrorDecoder$Default.decode(ErrorDecoder.java:91) ~[feign-core-9.5.0.jar:na]
    at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:138) ~[feign-core-9.5.0.jar:na]
    at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76) ~[feign-core-9.5.0.jar:na]
    at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103) ~[feign-core-9.5.0.jar:na]
    at com.sun.proxy.$Proxy120.queryAllConditions(Unknown Source) ~[na:na]
    at com.gezizhi.boss.controller.CrawlerConditionController.queryAllSource(CrawlerConditionController.java:29) ~[classes/:na]
    at com.gezizhi.boss.controller.CrawlerConditionController$$FastClassBySpringCGLIB$$bd843b81.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738) ~[spring-aop-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) [spring-aop-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85) ~[spring-aop-4.3.13.RELEASE.jar:4.3.13.RELEASE]

Конфигурация эврики: :

server:
  port: 8761
eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false
    fetch-registry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
  server:
    enable-self-preservation: false
    wait-time-in-ms-when-sync-empty: 0

И конфигурация клиента :

eureka:
  instance:
    lease-expiration-duration-in-seconds: 2
    lease-renewal-interval-in-seconds: 1
  client:
    serviceUrl:
      defaultZone: http://127.0.0.1:8761/eureka/

Код сервера:

  @RestController
    @RequestMapping("/api/crawler")
    public class CrawlerConditonApi {
        private final CrawlerConditonService crawlerConditonService;

        @Autowired
        public CrawlerConditonApi(CrawlerConditonService crawlerConditonService) {
            this.crawlerConditonService = crawlerConditonService;
        }

        @GetMapping("/conditions")
        public String queryAllConditions(String belongDatasource, String conditionStatus) {
            return crawlerConditonService.queryAllCondition(belongDatasource, conditionStatus);
        }

        @PostMapping("/conditions")
        public String insertConditon(String params, String belongDatasource) {
            return crawlerConditonService.insertConditon(params, belongDatasource);
        }

        @PutMapping("/conditions/{id}/status/{status}")
        public String updateCondition(@PathVariable("id") String id, @PathVariable("status") String status) {
            return crawlerConditonService.updateCondition(id, status);
        }
    }

КОД КЛИЕНТА:

@FeignClient(name = "CRAWLER-SERVICE")
public interface CrawlerServiceApi {
    @RequestMapping(value = "/api/papersources/", method = RequestMethod.GET)
    String queryAllSource();

    @RequestMapping(value = "/api/papersources/{id}/status/{status}", method = RequestMethod.PUT)
    String updateSource(@PathVariable("id") String id, @PathVariable("status") String status);

    @RequestMapping(value = "/api/crawler/conditions", method = RequestMethod.GET)
    String queryAllConditions(@RequestParam("belongDatasource") String belongDatasource,
                          @RequestParam("conditionStatus") String conditionStatus);

    @RequestMapping(value = "/api/crawler/conditions", method = RequestMethod.POST)
    String insertConditon(@RequestParam("params") String params,
                          @RequestParam("belongDatasource") String belongDatasource);

    @RequestMapping(value = "/api/crawler/conditions/{id}/status/{status}", method = RequestMethod.PUT)
    String updateCondition(@PathVariable("id") String id, @PathVariable("status") String status);
}

И я использую в контроллере:

@RestController
public class CrawlerConditionController {
    private final CrawlerServiceApi crawlerServiceApi;

    @Autowired
    public CrawlerConditionController(CrawlerServiceApi crawlerServiceApi) {
        this.crawlerServiceApi = crawlerServiceApi;
    }

    @GetMapping("/conditions/query")
    public AbstractResult queryAllSource(@RequestParam("belongDatasource") String belongDatasource,
                                         @RequestParam("conditionStatus") String conditionStatus) {
        return ApiInvokeRspUtil.returnDataRowsInvokeRsp("CRL00000",
                crawlerServiceApi.queryAllConditions(belongDatasource, conditionStatus));
    }

    @PostMapping("/conditions/add")
    public AbstractResult addConditon(@RequestParam("paramJson") String paramJson,
                                         @RequestParam("belongDataSource") String belongDataSource) {
        return ApiInvokeRspUtil.returnDataRowsInvokeRsp("CRL00000",
                crawlerServiceApi.insertConditon(paramJson, belongDataSource));
    }

    @PostMapping("/conditions/{id}/status/{status}")
    public AbstractResult updateConditon(@PathVariable("id") String id,
                                         @PathVariable("status") String status) {
        return ApiInvokeRspUtil.returnDataRowsInvokeRsp("CRL00000",
                crawlerServiceApi.updateCondition(id, status));
    }
}

application.yml, содержащий проект CrawlerConditonApi.

server:
  context-path: /crawler
  port: 8091

eureka:
  instance:
    lease-expiration-duration-in-seconds: 2
    lease-renewal-interval-in-seconds: 1
  client:
    serviceUrl:
      defaultZone: http://127.0.0.1:8761/eureka/

spring:
  datasource:
    driver-class-name: org.mariadb.jdbc.Driver
    url: jdbc:mysql://localhost:3306/gezizhi?useUnicode=true&characterEncoding=utf-8
    username: root
    password: password
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    filters: stat,wall,log4j
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password: password
    pool:
      max-idle: 10
      max-wait: 10000
      max-active: 1024
      min-idle: 1
    timeout: 3000
  application:
    name: crawler-service

mybatis:
  type-aliases-package: com.gezizhi.crawler.dao.domain
  mapper-locations: classpath:mybatis/*.xml

person Youngs    schedule 22.03.2018    source источник
comment
Как вы вызываете URL-адрес ресурса с помощью FeignClient?   -  person Mehraj Malik    schedule 22.03.2018
comment
Я уже редактировал свой вопрос, пожалуйста, посмотрите добавленный код, спасибо!   -  person Youngs    schedule 22.03.2018
comment
ваш crawler-service правильно зарегистрирован на сервере Eureka? не могли бы вы проверить журналы?   -  person gWombat    schedule 22.03.2018
comment
@gWombat да, я могу показать сервис в админке eureka   -  person Youngs    schedule 22.03.2018
comment
@Mehraj Malik Ни один из них не может работать.   -  person Youngs    schedule 22.03.2018
comment
@Youngs никогда не публикуют конфиденциальную информацию типа Password, я редактировал вопрос.   -  person Mehraj Malik    schedule 22.03.2018
comment
@Mehraj Malik Спасибо, этот пароль является моим локальным паролем базы данных, я не буду использовать его в общедоступной сетевой среде. Еще раз спасибо за совет, и я запомню его.   -  person Youngs    schedule 22.03.2018
comment
Feign не использует эврика, поскольку вы используете атрибут url для @FeignClient.   -  person spencergibb    schedule 02.04.2018
comment
На своем сервере Eureka убедитесь, что вы добавили @EnableEurekaServer, а в своем клиенте убедитесь, что вы добавили оба: @EnableEurekaClient & @EnableFeignClients   -  person Luay Abdulraheem    schedule 09.04.2018
comment
@Youngs, если вы нашли решение, не забудьте опубликовать его.   -  person Anders Metnik    schedule 06.03.2019
comment
@AndersMetnik извините, на данный момент решения нет.   -  person Youngs    schedule 06.03.2019
comment
@Youngs только что заставили меня работать, как у вас классы приложений?   -  person Anders Metnik    schedule 06.03.2019


Ответы (1)


Это старый вопрос, я все еще отправляю свой ответ, чтобы он мог помочь кому-то другому, поскольку у меня была та же проблема, и я, наконец, смог ее решить.

Это произошло из-за того, что server.context установлен на crawler. Поскольку это эффективно добавляет новый сегмент URL-адреса, вам необходимо изменить своего воображаемого клиента на ниже (обратите внимание на контекст, добавленный после имени службы)

@FeignClient(name = "CRAWLER-SERVICE/crawler")

Или вам нужно изменить RequestMapping на что-то вроде ниже (опять же, обратите внимание на контекст, добавленный перед URL-адресом службы):

@RequestMapping("crawler/<rest of the url>")
person Aakash    schedule 24.12.2020