好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

SpringBoot工程下使用OpenFeign的坑及解决

一、前言

在 SpringBoot 工程(注意不是SpringCloud)下使 OpenFeign 的大坑。为什么不用SpringCloud中的Feign呢?

首先我的项目比较简单(目前只有login与业务模块)所以暂时不去引入分布式的架构,但两个服务之间存在一些联系因此需要接口调用接口(实现该操作方式很多我选择了OpenFeign,踩坑之路从此开始。。。)。

二、具体的坑

使用OpenFeign我是直接参考官方的demo,官方的例子写的简洁明了直接套用到自己的工程中即可,自己也可以做相应的封装再调用但demo中使用到了一个feign的核心注解@RequestLine,问题就是出在该注解上。

此时你去做调试如果使用的是GET请求,被请求的接口则会收到POST的请求然后A接口(请求方)就报500的错误,B接口(被请求方)则提示接口不支持POST请求(不支持POST请求是非常正常的,因为B接口定义的method是GET方法)。

以下是我的代码片段:

自定义UserFeign接口

?

1

2

3

4

5

6

7

8

9

public interface UserFeign {

     /**

      * 根据userId获取用户信息

      * @param userId

      * @return

      */

     @RequestLine ( "GET /user/getUserById?id={id}" )

     Result getUserById( @Param ( "id" ) String userId);

}

调用UserFeign接口

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

@Service

public class UserService{

     /**

      * 通过OpenFegin实现接口调用接口

       * @param userId

      * @return

      */

     public Result getUserByIdWith(String userId) {

         UserFeign userInfo = Feign.builder()

                 .decoder( new JacksonDecoder())

                 .target(UserFeign. class , "http://localhost:8080" );

         Result res = userInfo.getUserById(userId);

         return res;

     }

}

A接口 (请求方)

 

?

1

2

3

4

5

@RequestMapping (value = "/test" , method = RequestMethod.GET)

public Result test() {

     String id = "ad545461300a" ;

     return userService.getUserByIdWith(id);

}

B接口 (被请求方)

?

1

2

3

4

5

6

7

8

9

10

11

@RequestMapping (value = "/getUserById" , method = RequestMethod.GET)

public Result getUserByUserId( @RequestParam (required = true ) String id){

     if ( "" .equals(id)) {

         throw new BusinessException( 400 , "userId不能为空!" );

     }

     Users info = usersService.getUserById(id);

     if (info == null ) {

         throw new BusinessException( 404 , "userId有误!" );

     }

     return ResultUntil.success(info);

}

以上代码我做了一些小调整,将调用UesrFeign接口中的方法封装在UserService中并且使用了@service这样我就可以在其它地方直接注入UserService然后调用其中方法。

你会觉得以上代码跟官网的demo没啥区别但官方文档中并没有说明使用@RequestLine注解需要进行配置(事实上需要进行配置的)。

配置代码如下:

?

1

2

3

4

@Bean

public Contract useFeignAnnotations() {

     return new Contract.Default();

}

完成以上的配置就可以进行正常的调用了,该问题困扰我好几天了今天终于解决了(真不容易),希望该文章没有白写。

最后感谢 这篇文章 让我在放弃的时候找到了思路。(调试中遇到的细节问题就不在此进行赘述了)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/feiyst/article/details/88677223

查看更多关于SpringBoot工程下使用OpenFeign的坑及解决的详细内容...

  阅读:24次