SpringCloud Feign遇到的问题

2017-12-06遇到的问题,调试了一天...

Posted by Yezhiwei on December 7, 2017

问题一:由于马虎,缺少配置,报错如下:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.gemantic.springcloud.service.AdditionClient': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: Method add not annotated with HTTP method type (ex. GET, POST)


Caused by: java.lang.IllegalStateException: Method add not annotated with HTTP method type (ex. GET, POST)

解决方案,在Feign接口上没有配置请求式,在接口上增加请求方式@GetMapping(value = "/add")@RequestMapping(value = "/add"),完整代码如下:

@FeignClient("springcloud-addition-service")
public interface AdditionClient {

    /**
     * 加法接口
     * @param a
     * @param b
     * @return
     */
//    @RequestMapping(value = "/add")
    @GetMapping(value = "/add")
    ResponseEntity<ResultData> add(@RequestParam("a") @NotNull Integer a, @RequestParam("b") @NotNull Integer b);
}

注: value = "/add" 与真正服务一致。

问题二:

Caused by: java.lang.IllegalStateException: RequestParam.value() was empty on parameter 0

暴漏Restful服务的方法如下:

@Slf4j
@RestController
@Api(description = "加法接口")
public class AdditionController {

    @Autowired
    private Addition addition;

    @GetMapping(value = "/add")
    @ApiOperation(value = "a + b = ?")
    public ResponseEntity<ResultData> add(@RequestParam @NotNull Integer a, @RequestParam @NotNull Integer b) {

        if (log.isInfoEnabled()) {
            log.info("add {} + {}", a, b);
        }
        int result = addition.add(a, b);
        ResultData resultData = ResultData.builder().message(Message.builder().code(0).message(Message.SUCCESS_MESSAGE).build()).build();
        resultData.setData(result);
        return ResponseEntity.ok(resultData);
    }
}

Feign的方式的接口如下:

@GetMapping(value = "/add")
ResponseEntity<ResultData> add(@RequestParam @NotNull Integer a, @RequestParam @NotNull Integer b);

服务启动时就会报错误:

Caused by: java.lang.IllegalStateException: RequestParam.value() was empty on parameter 0

解决方案:在@RequestParam 增加方法名

@GetMapping(value = "/add")
ResponseEntity<ResultData> add(@RequestParam("a") @NotNull Integer a, @RequestParam("b") @NotNull Integer b);

注:@PathVariable@ RequestParam 类似的。

问题三:

Caused by: java.lang.IllegalStateException: Method has too many Body parameters: public abstract org.springframework.http.ResponseEntity com.gemantic.springcloud.service.AdditionClient.add(java.lang.Integer,java.lang.Integer)

解决方案:当使用Feign时,如果发送的是get请求,那么需要在请求参数前加上@RequestParam@PathVariable注解修饰,Controller里面可以不加该注解修饰。

@GetMapping(value = "/add")
ResponseEntity<ResultData> add(@RequestParam("a") @NotNull Integer a, @RequestParam("b") @NotNull Integer b);