SpringCloud-feign组件

悠悠 2023-07-18 11:14 125阅读 0赞

方面微服务之间的调用、访问 因为restTemplate使用虽然简单,但是在访问方需要指定被调用方的微服务名、url,这样在开发过程中、后期要进行为期其实非常麻烦。

SpringCloud提供了feign组件解决

用法类似于mybatis里面的mapper

xml sqlsession.xxxList(“com.woniuxy.product.findById”,”1001”)
mapper interface public List findById(int id) mapper.findById()
使用feign的时候也是通过对应的接口API调用就完事,不需要调用方自己去知道对方微服务名、url是什么,只需要通过接口调就行了

①在父工程的pom里面引入feign的依赖 openfeign

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-openfeign-core</artifactId>
  4. <version>2.1.0.RELEASE</version>
  5. </dependency>

②在user模块中引入feign的依赖

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-openfeign</artifactId>
  4. <version>2.1.0.RELEASE</version>
  5. </dependency>

③在commons(公共)模块引入feign的依赖

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-openfeign</artifactId>
  4. <version>2.1.0.RELEASE</version>
  5. </dependency>

④被调用方负责在commons模块中去编写接口,内容如下:

在编写接口的时候,可以直接去拷贝handler中的方法,粘贴到接口中,只需要将方法体删除,如果在类上@ReuestMapping指定的前缀url,那么需要给每个方法的url加上该前缀
在这里插入图片描述

⑤在需要使用该接口的地方(user模块的handler中)注入该接口,然后将之前restTemplate调用方式替换掉

在这里插入图片描述

⑥在user模块的启动类上添加注解扫描该接口所在的包(commons中的)

在这里插入图片描述
⑦分别启动eureka、8001、8002、user,浏览器发送url请求
http://localhost/user/all

获得数据,over!

发表评论

表情:
评论列表 (有 0 条评论,125人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Storm

    一 Strom主从结构 ![SouthEast][] 二 主从结构与对称结构 主从结构:简单、高效,但主节点存在单点问题 对称结构:复杂、效率较低,但无单点问题,更加可

    相关 Vue

    Vue组件 1. 什么是组件 1. 组件的概念:组件即自定义控件,是Vue.js最强大的功能之一 2. 组件的用途:组件能够封装可重用代码,扩展html标签功能