SpringCloud openfeign @FeignClient注解的path参数不起作用? 迈不过友情╰ 2021-06-24 13:58 706阅读 0赞 本地测试时发现,请求`http://localhost:9999/addLabel`是可以的, 请求`http://localhost:9999/cms/addLabel`会报404。 接口是这样写的 @FeignClient(name = "image-server" path = "/cms") public interface ImageLabelServiceCmsFeign { @PostMapping(value = "/addLabel") Result<Void> addLabel( @RequestParam(name = "parentLabelId") Integer parentLabelId, @RequestParam(name = "labelName") String labelName); } 服务实现是这样的 @RestController public class ImageLabelServiceCmsFeignImpl implements ImageLabelServiceCmsFeign { @Override public Result<Void> addLabel(Integer parentLabelId, String labelName) { // ... } } 启动类是这样的 @EnableFeignClients(basePackages = {"com.xx"}) @SpringBootApplication public class Application implements InitializingBean { public static void main(String[] args) { new SpringApplicationBuilder().sources(Application.class) .web(WebApplicationType.SERVLET) .run(args); } } 项目的依赖是这样的,使用了`eureka`作为服务注册中心。 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.1.0.RELEASE</version> </dependency> <!-- spring cloud --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <version>2.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>2.1.0.RELEASE</version> </dependency> FeignClient是一个“客户端”,它是用来发起请求的,不是提供服务的。 你配置FeignClient的path只影响它去请求的地址,不影响服务的地址,如果你的服务路径没有那个`/cms`自然就请求不到了 **接口改成这样,实现不变(推荐)** @FeignClient(name = "image-server")//①去掉path参数 @RequestMapping("/cms")//②增加注解 public interface ImageLabelServiceCmsFeign { @PostMapping(value = "/addLabel") Result<Void> addLabel( @RequestParam(name = "parentLabelId") Integer parentLabelId, @RequestParam(name = "labelName") String labelName); } **或者接口不变,实现类加`@RequestMapping("/cms")`也可以** -------------------- **@FeignClient的path参数只对FeignClient的请求路径起作用,不会对restcontroller实现起作用,而接口上的requestMapping(包括衍生的GetMapping之类)会同时对FeignClient和Restcontroller起作用** **不加path参数的话FeignClient的请求路径和服务的路径是一致的,可以调用成功。加了`path="/cms"`参数后,要想两边路径一致,就需要在实现上加`@RequestMapping("/cms")`或配置项目的`context-path=/cms`使请求路径和服务路径一致**
还没有评论,来说两句吧...