在Spring Boot中使用Feign时将URL翻倍

时间:2018-11-22 05:53:05

标签: spring-boot spring-cloud-feign

我对Spring Boot并不陌生,并且正在使用Feign Rest客户端与我的Web服务进行通信。但是我的URL加倍,无法调用预期的服务。

@FeignClient(name= "exchange-service", url="localhost:8000")

公共接口ExchangeServiceProxy {

@GetMapping
@RequestMapping(value = "/exchange/from/{from}/to/{to}")
public ExchangeBean retrieveExchangeValue(@PathVariable("from") String from,
        @PathVariable("to") String to);

}

 status 404 reading 
ExchangeServiceProxy#retrieveExchangeValue(String,String); content:
{"timestamp":"2018-11-22T05:50:45.822+0000","status":404,"error":"Not 
Found","message":"No message 
available","path":"/exchange/from/USD/to/XYZ/exchange/from/USD/to/XYZ"}

2 个答案:

答案 0 :(得分:2)

您尚未在问题中放入Spring Starter类。如果您使用Feign进行客户端负载平衡,则@EnableFeignClients足以放入Spring入门类。我认为您已经将@GetMapping和@RequestMapping都放入了ExchangeServiceProxy中,这是不必要的。由于您已在@RequestMapping中指定了网址格式,因此请删除@GetMapping。这可能导致您的网址加倍。

@FeignClient(name= "exchange-service", url="localhost:8000")
public interface ExchangeServiceProxy {

@RequestMapping(value = "/exchange/from/{from}/to/{to}")
public ExchangeBean retrieveExchangeValue(@PathVariable("from") String 
from,
        @PathVariable("to") String to);
}

如果您具有 url =“ localhost:8000” 这样的硬编码,则它将仅对在端口8000下运行的实例起作用。使用Ribbon和Eureka命名服务器是理想的选择如果您的意图是我刚才提到的,则可以充分利用客户端负载平衡。

答案 1 :(得分:0)

您需要在@EnableFeignClients之后在主类中添加@SpringBootApplication,如下所示:

@SpringBootApplication
@ComponentScan
@EnableScheduling
@EnableAsync
@EnableZuulProxy
@EnableFeignClients
public class ExampleApplication extends SpringBootServletInitializer{
    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }


}

然后为FeignClient创建一个接口,如下所示:

@FeignClient(name = "service_name", url = "http://localhost:port_to_the_another_application")
public interface ExampleFeignClient {

    @RequestMapping(value = "/mapping", method = RequestMethod.POST)
    String createUserWallet(@RequestHeader("Authorization") String jwtToken);
}

我希望这会有所帮助。