当前位置: 代码网 > it编程>编程语言>Java > Spring Cloud实现远程调用OpenFeign组件的方法

Spring Cloud实现远程调用OpenFeign组件的方法

2026年02月03日 Java 我要评论
一、resttemplate存在问题观察之前文章介绍的远程调用的代码:public orderinfo selectorderbyid(integer orderid) { orderi

一、resttemplate存在问题

观察之前文章介绍的远程调用的代码:

public orderinfo selectorderbyid(integer orderid) {
        orderinfo orderinfo = ordermapper.selectorderbyid(orderid);
        string url = "http://product-service/product/"+ orderinfo.getproductid();
        productinfo productinfo = resttemplate.getforobject(url,
                productinfo.class);
        orderinfo.setproductinfo(productinfo);
        return orderinfo;
    }

虽说resttemplate 对http封装后, 已经比直接使用httpclient简单方便很多, 但是还存在一些问题.

  1. 需要拼接url, 灵活性高, 但是封装臃肿, url复杂时, 容易出错.
  2. 代码可读性差, 风格不统⼀.

微服务之间的通信方式, 通常有两种: rpc 和 http.
在springcloud中, 默认是使用http来进行微服务的通信, 最常用的实现形式有两种:
• resttemplate
• openfeign

rpc(remote procedure call)远程过程调用,是⼀种通过网络从远程计算机上请求服务,而不需
要了解底层网络通信细节。rpc可以使用多种网络协议进行通信, 如http、tcp、udp等, 并且在
tcp/ip网络四层模型中跨越了传输层和应用层。简言之rpc就是像调用本地方法⼀样调用远程方法。
常见的rpc框架有:
1 . dubbo: apache dubbo 中文
2 . thrift : apache thrift - home
3 . grpc: grpc

二、openfeign介绍

openfeign 是一个声明式的 web service 客户端. 它让微服务之间的调用变得更简单, 类似controller调用service, 只需要创建⼀个接口,然后添加注解即可使用openfeign.

openfeign 的前身
feign 是 netflix 公司开源的⼀个组件.
• 2013年6月, netflix发布 feign的第⼀个版本 1.0.0
• 2016年7月, netflix发布feign的最后⼀个版本 8.18.0

2016年,netflix 将 feign 捐献给社区
• 2016年7月 openfeign 的首个版本 9.0.0 发布,之后⼀直持续发布到现在.

spring cloud feign

spring cloud feign 是 spring 对 feign 的封装, 将 feign 项目集成到 spring cloud ⽣态系统中.受 feign 更名影响,spring cloud feign 也有两个 starter

spring-cloud-starter-feign
spring-cloud-starter-openfeign

由于feign的停更维护, 对应的, 我们使用的依赖是 spring-cloud-starter-openfeign。

openfeign :官方文档
spring cloud feign:官方文档

三、快速上手

3.1 引入依赖

<dependency>
  <groupid>org.springframework.cloud</groupid>
  <artifactid>spring-cloud-starter-openfeign</artifactid>
</dependency>

3.2 添加注解

在order-service的启动类添加注解 @enablefeignclients , 开启openfeign的功能.

    @enablefeignclients
    @springbootapplication
    public class orderserviceapplication {
        public static void main(string[] args) {
            springapplication.run(orderserviceapplication.class, args);
        }
    }

3.3 编写openfeign的客户端

基于springmvc的注解来声明远程调用的信息

    @feignclient(value = "product-service", path = "/product")
    public interface productapi {
        @requestmapping("/{productid}")
        productinfo getproductbyid(@pathvariable("productid") integer productid);
    }

@feignclient 注解作用在接口上, 参数说明:

• name/value:指定feignclient的名称, 也就是微服务的名称, 用于服务发现, feign底层会使用spring cloud loadbalance进行负载均衡. 也可以使用 url 属性指定⼀个具体的url.
• path: 定义当前feignclient的统一前缀.

3.4 远程调用

修改远程调用的方法

    @autowired
    private productapi productapi;
    /**
     * feign实现远程调⽤
     * @param orderid
     */
    public orderinfo selectorderbyid(integer orderid) {
        orderinfo orderinfo = ordermapper.selectorderbyid(orderid);
        productinfo productinfo =
                productapi.getproductbyid(orderinfo.getproductid());
        orderinfo.setproductinfo(productinfo);
        return orderinfo;
    }

不同方式之间代码对比:

四、openfeign参数传递

通过观察, 我们也可以发现, feign的客户端和服务提供者的接口声明非常相似
上面例子中, 介绍了feign 从url中获取参数, 接下来介绍下feign参数传递的其他方式。

4.1 传递单个参数

服务提供方:product-service

    @requestmapping("/product")
    @restcontroller
    public class productcontroller {
        @requestmapping("/p1")
        public string p1(integer id){
            return "p1接收到参数:"+id;
        }
    }

feign客户端:

    @feignclient(value = "product-service", path = "/product")
    public interface productapi {
        @requestmapping("/p1")
        string p1(@requestparam("id") integer id);
    }

服务消费方order-service:

    @requestmapping("/feign")
    @restcontroller
    public class testfeigncontroller {
        @autowired
        private productapi productapi;
        @requestmapping("/o1")
        public string o1(integer id){
            return productapi.p1(id);
        }
    }

测试远程调用:
http://127.0.0.1:8080/feign/o1?id=5
测试结果:

4.2 传递多个参数

使用多个@requestparam 进行参数绑定即可

服务提供方 product-service

    @requestmapping("/p2")
    public string p2(integer id,string name){
        return "p2接收到参数,id:"+id +",name:"+name;
    }

feign客户端:

    @feignclient(value = "product-service", path = "/product")
    public interface productapi {
       @requestmapping("/p2")
       string p2(@requestparam("id")integer id,@requestparam("name")string name);
    }

服务消费方order-service:

    @requestmapping("/o2")
    public string o2(@requestparam("id")integer id,@requestparam("name")string name){
        return productapi.p2(id,name);
    }

测试远程调用:

http://127.0.0.1:8080/feign/o2?id=5&name=zhangsan

4.3 传递对象

服务提供方 product-service

   @requestmapping("/p3")
    public string p3(productinfo productinfo){
        return "接收到对象, productinfo:"+productinfo;
    }

feign客户端:

@requestmapping("/p3")
string p3(@springquerymap productinfo productinfo);

服务消费方order-service:

    @requestmapping("/o3")
    public string o3(productinfo productinfo){
        return productapi.p3(productinfo);
    }

4.4 传递json

服务提供方 product-service:

    @requestmapping("/p4")
    public string p4(@requestbody productinfo productinfo){
        return "接收到对象, productinfo:"+productinfo;
    }

feign客户端

@requestmapping("/p4")
string p4(@requestbody productinfo productinfo);

服务消费方order-service:

   @requestmapping("/o4")
    public string o4(@requestbody productinfo productinfo){
        system.out.println(productinfo.tostring());
        return productapi.p4(productinfo);
    }

五、最佳实践

最佳实践, 其实也就是经过历史的迭代, 在项目中的实践过程中, 总结出来的最好的使用方式.
通过观察, 我们也能看出来, feign的客户端与服务提供者的controller代码非常相似

feign 客户端:

    @feignclient(value = "product-service", path = "/product")
    public interface productapi {
        @requestmapping("/{productid}")
        productinfo getproductbyid(@pathvariable("productid") integer productid);
    }

服务提供方controller:

    @requestmapping("/product")
    @restcontroller
    public class productcontroller {
        @requestmapping("/{productid}")
        public productinfo getproductbyid(@pathvariable("productid") integer productid){
            //...
        }
    }

有没有⼀种方法可以简化这种写法呢?

5.1 feign继承方式

feign 支持继承的方式, 我们可以把⼀些常件的操作封装到接口里.
我们可以定义好⼀个接口, 服务提供方实现这个接口, 服务消费方编写feign 接口的时候, 直接继承这个接口

5.1.1 创建一个module

接口可以放在⼀个公共的jar包里, 供服务提供方和服务消费方使用

5.1.2 引入依赖

<dependencies>
  <dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-web</artifactid>
  </dependency>
  <dependency>
   <groupid>org.springframework.cloud</groupid>
   <artifactid>spring-cloud-starter-openfeign</artifactid>
  </dependency>
</dependencies>

5.1.3 编写接口

复制 productapi, productinfo 到product-api模块中

 public interface productinterface {
        @requestmapping("/{productid}")
        productinfo getproductbyid(@pathvariable("productid") integer productid);
        @requestmapping("/p1")
        string p1(@requestparam("id") integer id);
        @requestmapping("/p2")
        string p2(@requestparam("id")integer id,@requestparam("name")string name);
        @requestmapping("/p3")
        string p3(@springquerymap productinfo productinfo);
        @requestmapping("/p4")
        string p4(@requestbody productinfo productinfo);
    }

5.1.4 服务提供方

服务提供方实现接口productinterface:

 @requestmapping("/product")
    @restcontroller
    public class productcontroller implements productinterface {
        @autowired
        private productservice productservice;
        @requestmapping("/{productid}")
        public productinfo getproductbyid(@pathvariable("productid") integer
                                                  productid){
            system.out.println("收到请求,id:"+productid);
            return productservice.selectproductbyid(productid);
        }
        @requestmapping("/p1")
        public string p1(integer id){
            return "p1接收到参数:"+id;
        }
        @requestmapping("/p2")
        public string p2(integer id,string name){
            return "p2接收到参数,id:"+id +",name:"+name;
        }
        @requestmapping("/p3")
        public string p3(productinfo productinfo){
            return "接收到对象, productinfo:"+productinfo;
        }
        @requestmapping("/p4")
        public string p4(@requestbody productinfo productinfo){
            return "接收到对象, productinfo:"+productinfo;
        }
    }

5.1.5 服务消费方

服务消费方继承productinterface

@feignclient(value = "product-service", path = "/product")
public interface productapi extends productinterface {
}

这样通过继承就可以实现远程调用

5.2 feign 抽取方式

官方推荐feign的使用方式为继承的方式, 但是企业开发中, 更多是把feign接口抽取为⼀个独立的模块(做法和继承相似, 但理念不同).
操作方法:
将feign的client抽取为⼀个独立的模块, 并把涉及到的实体类等都放在这个模块中, 打成⼀个jar. 服务消费方只需要依赖该jar包即可. 这种方式在企业中比较常见, jar包通常由服务提供方来实现.

5.2.1 创建新module

5.2.2 引入依赖

<dependency>
  <groupid>org.springframework.cloud</groupid>
  <artifactid>spring-cloud-starter-openfeign</artifactid>
</dependency>

5.2.3 编写api

复制 productapi, productinfo 到product-api模块中
之后通过maven打包,可以观察maven本地仓库检查是否打包成功

5.2.4 服务消费方使用product-api

1 删除 productapi, productinfo.
2. 引入依赖:

<dependency>
 <groupid>org.example</groupid>
 <artifactid>product-api</artifactid>
 <version>1.0-snapshot</version>
</dependency>

修改项目中productapi, productinfo的路径为product-api中的路径

3 .指定扫描类: productapi
在启动类添加扫描路径

    @enablefeignclients(basepackages = {"com.bite.api"})
    @springbootapplication
    public class orderserviceapplication {
        public static void main(string[] args) {
            springapplication.run(orderserviceapplication.class, args);
        }
    }

也可以指定需要加载的feign客户端
@enablefeignclients(clients = {productapi.class})

六、总结

以上就是本文全部内容,本文主要为大家介绍了spring cloud中实现远程调用的另一个组件-openfeign的相关知识与操作。感谢各位能够看到最后,如有问题,欢迎各位大佬在评论区指正,希望大家可以有所收获!创作不易,希望大家多多支持。

到此这篇关于spring cloud实现远程调用openfeign组件的方法的文章就介绍到这了,更多相关spring cloud调用openfeign内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com