研习springboot的feign时,遇到了这样的一个坑,由于本人愚钝,特记载下来方便以后翻阅。
问题描述:配置了FeignConfiguration,里面仅仅做了eureka的权限处理,like this:
@Configuration
public class FeignConfiguration{
//为FeignConfiguration添加链接eureka的权限
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("seven", "pwd123456");
}
}
然后在FeignClient中声明开放接口
@FeignClient(name="sss",url="localhost:8761",configuration=FeignConfiguration.class)
public interface IfeignInter {
@RequestLine("GET /eureka/apps/{serviceName}")
public String getServiceInfoByserviceName(@Param("serviceName") String serviceName) ;
}
然后启动服务报错:Method getServiceInfoByserviceName not annotated with HTTP method type (ex. GET, POST)
各类坑的解决方法如下:
在spingboot中定义feign的对外开放接口:
@FeignClient(name="sss",url="localhost:8761",configuration=FeignConfiguration.class)
public interface IfeignInter {
//1.@GetMapping("/eureka/apps/{serviceName}")@PathVariable("serviceName")
//2.@RequestMapping(value="/eureka/apps/{serviceName}", method=RequestMethod.GET)@PathVariable("必须有值")
//3.@RequestLine("GET /eureka/apps/{serviceName}")@Param("serviceName")
@RequestLine("GET /eureka/apps/{serviceName}")public String getServiceInfoByserviceName(@Param("serviceName") String serviceName) ;
}
自定义feign的config:
@Configuration
public class FeignConfiguration{
//使用feign的注解方式
@Bean
public Contract useFeignAnnotations() {
return new Contract.Default();
}
//为FeignConfiguration添加链接eureka的权限
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("seven", "pwd123456");
}
}
1.不支持@GetMapping这样的混合注解只能使用@RequestMapping(value="/simple/{id}",method=RequestMethod.GET)这种方式来实现混合注解。
2.对于url路径上的PathVariable属性必须要有默认值,否者会报PathVariable annotation was empty on param 0.
3.这个就是当时我纠结了两个小时的坑,最后翻看Contract.Default()的源码才明白,如果FeignClient想要使用feign自己定义的注解,需要在configuration中配置feign的契约模式,因为其默认采用的时sping的注解方式,所以会不识别feign的注解,导致Method getServiceInfoByserviceName not annotated with HTTP method type (ex. GET, POST)。
这种异常情况下的解决方法有两种:
一种就是使用sping默认的注解方式
@RequestMapping(value="/eureka/apps/{serviceName}", method=RequestMethod.GET)@PathVariable("必须有值")
eg:
@RequestMapping(value="/eureka/apps/{serviceName}", method=RequestMethod.GET)
public String getServiceInfoByserviceName(@PathVariable("serviceName") String serviceName) ;}
另外一种就是在configuration中配置feign的契约模式
eg:
@Configuration
public class FeignConfiguration {
//Contract feign的默认契约
@Bean
public Contract feignContract() {
return Contract.Default();
}
}
这样就可以正常创建启动了。