Loading [MathJax]/jax/input/TeX/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >spring cloud 入门系列五:使用Feign 实现声明式服务调用

spring cloud 入门系列五:使用Feign 实现声明式服务调用

作者头像
全栈程序员站长
发布于 2022-07-18 08:19:11
发布于 2022-07-18 08:19:11
40700
代码可运行
举报
运行总次数:0
代码可运行

大家好,又见面了,我是全栈君。

一、Spring Cloud Feign概念引入 通过前面的随笔,我们了解如何通过Spring Cloud ribbon进行负责均衡,如何通过Spring Cloud Hystrix进行服务断路保护, 两者作为基础工具类框架应用在各种基础设施类微服务和业务类微服务中,并且成对存在,那么有没有更高层的封装,将两者的使用 进一步简化呢? 有! 他就是Spring Cloud Feign。它基于Netflix Feign实现,整合了Spring Cloud Ribbon和Spring Cloud Hystrix, 除了提供两者强大的功能外,还提供了一种声明式的Web服务客户端定义方式。

二、入门实例 我们还是继续使用前面随笔中的hello-service服务,这里通过Spring Cloud Feign提供的声明式服务绑定功能来实现对服务接口的调用。 我们需要新建一个feign-consumer来代替之前的hello-consumer

先给出代码结构:

代码实现:

  1. 新建maven工程(feign-consumer)
  2. 修改pom文件,引入eureka和feign依赖
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sam</groupId>
  <artifactId>feign-consumer</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>

    <properties>
        <javaVersion>1.8</javaVersion>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR6</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>

    </dependencyManagement>

    <dependencies>
        <!-- 引入eureka 客户端依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <!-- 引入feign 依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>

    </dependencies>
    
</project>
 
 

  1. 新建启动类
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/**
 * 通过@EnableFeignClients来开启spring cloud feign的支持功能
 *
 */
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeiApp {

    public static void main(String[] args) {
        SpringApplication.run(FeiApp.class, args);
    }

}
 

  1. 新建service接口
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/**
 * 通过@FeignClient注解指定服务名来绑定服务,这里的服务名字不区分大小写
 * 然后再通过@RequestMapping来绑定服务下的rest接口
 *
 */
@FeignClient(name="hello-service")
public interface FeignConsumerService{

    @RequestMapping("/hello")
    public void hello();
}
 
 

  1. 新建controller
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@RestController
public class FeiConsumerController {

    @Autowired
    FeignConsumerService consumerService;

    @RequestMapping("feign-consumer")
    public String feignConsumer() {
        consumerService.hello();
        return "feign consumer call finished!!!";
    }

}
 
 

  1. 新建application.properties
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
server.port=9001

spring.application.name=feign-consumer

eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka
 
 

  1. 测试,
    1. 启动服务注册中心eureka、启动两个hello-service(端口号分别为9090和9091),启动feign-consumer
    1. 访问http://localhost:9001/feign-consumer

      并且多次访问的话,会轮询调用两个hello-service服务。

三、参数绑定 在上面的例子中,我们实现的只是一个不带参数的rest服务绑定,然而现实的业务中不会这么简单,往往会有各种参数, 这个时候我们做如下事情:

  1. 如果服务提供方有对象参数(如User对象),那么feign-consumer工程中需要建一个路径和类名完全一样的类。
  2. 然后将服务提供方controller里面的所有方法声明进行copy(包括前面的@RequestMapping),粘贴到feign-consumer的service接口里面。

四、继承特性 根据上面参数绑定的做法,我们需要进行很多copy操作,这样比较麻烦,可以通过继承的方式进行简化。

这种实现步骤如下:

1.我们需要新建一个基础工程hello-service-api,

  代码结构:

  代码实现:

  1. )新建maven项目hello-service-api

)修改pom文件

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sam</groupId>
  <artifactId>hello-service-api</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>

    <properties>
        <javaVersion>1.8</javaVersion>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
    </dependencies>
</project>
 

你会发现其实就是一个普通的spring boot项目。

)考虑到需要掩饰参数中有对象的情况,我们加个User类

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package com.sam.entity;

public class User {

    private String name;
    private Integer age;

    
    public User(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }
    

    public User() {
        super();
    }



    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

}
 
 

User必须要有一个无参数的构造器。

新建service接口

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/**
 * 为了同前面那个hello 接口区分开了,我们加了refactor前缀
 *
 */
@RequestMapping("/refactor")
public interface HelloService {

    @RequestMapping("/hello2")
    public String hello2();
    
    @RequestMapping("/hello3")
    public User printUser(@RequestBody User user);
}
 
 

2.重构hello-sevice服务

  1. )修改pom文件
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<!-- 引入 hello-service-api的依赖,以继承其提供的接口 -->
        <dependency>
            <groupId>com.sam</groupId>
            <artifactId>hello-service-api</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
 
 

)HelloController implements HelloService,并实现interface中的接口

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@RestController
public class HelloController implements HelloService{

    Logger logger = LoggerFactory.getLogger(HelloController.class);

    @Autowired
    DiscoveryClient discoveryClient;
    
    @RequestMapping("/hello")
    public String hello() throws Exception {
        ServiceInstance instance = discoveryClient.getLocalServiceInstance();
        //打印服务的服务id
        logger.info("*********" + instance.getServiceId());
        return "hello,this is hello-service";
    }

    @Override public String hello2() { return "hello,this is hello2-service"; } @Override public User printUser(@RequestBody User user) { return user; } 
}
 

controller实现接口的方法时,不需要@RequestMapping注解,只需要类注解@RestController即可。

3.重构feign-consumer服务

  1. )修改POM文件
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<!-- 引入 hello-service-api的依赖,以继承其提供的接口 -->
        <dependency>
            <groupId>com.sam</groupId>
            <artifactId>hello-service-api</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
 

)让FeignConsumerService extends hello-service-api中的HelloService

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/**
 * 通过@FeignClient注解指定服务名来绑定服务,这里的服务名字不区分大小写
 * 然后再通过@RequestMapping来绑定服务下的rest接口
 *
 */
@FeignClient(name="hello-service")
public interface FeignConsumerService extends HelloService{

    @RequestMapping("/hello")
    public void hello();
}
 

只需要继承即可。

修改controller,追加方法

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@RestController
public class FeiConsumerController {

    @Autowired
    FeignConsumerService consumerService;

    @RequestMapping("feign-consumer")
    public String feignConsumer() {
        consumerService.hello();
        return "feign consumer call finished!!!";
    }
 @RequestMapping("feign-consumer-user") public User feignConsumer2(User user) { consumerService.hello2(); return consumerService.printUser(user); }
}
  
 

4.测试

五、其他 由于Spring Cloud Feign是通过ribbon和hystrix实现具体功能的,因此可以直接通过配置这两个来实现功能 1.ribbon配置方式:   通过ribbon.<key>=<value>的方式进行全局配置,比如     ribbon.ConnectTimeout=500     ribbon.ReadTimeout=5000   通过<client>.ribbon.<key>=<value>的方式进行指定服务配置,比如     #这里的<client>为@FeignClient(value=”hello-service”)指定的服务名     hello-service.ribbon.ConnectTimeout=500     hello-service.ribbon.ReadTimeout=500 2.hystrix配置方式:   通过hystrix.command.default.xxx进行全局配置     如:hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000   通过hystrix.command.<commandKey>.xxx进行指定配置,这里的<commandKey>可以为方法名     如:hystrix.command.hello.execution.isolation.thread.timeoutInMilliseconds=5000 3.请求压缩配置,支持对请求和响应进行GZIP压缩,以减少通信过程中的性能损耗。   feign.compression.request.enabled=true;

  feigan.compression.response.enabled=true;

4.日志配置   Spring Cloud Feign在构建被@FeignClient注解修饰的服务客户端是,会为每一个客户端都创建一个feign.Logger实例,我们可以利用该日志对象进行Log分析。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/120906.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年2月1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
spring cloud 入门系列四:使用Hystrix 实现断路器进行服务容错保护「建议收藏」
在微服务中,我们将系统拆分为很多个服务单元,各单元之间通过服务注册和订阅消费的方式进行相互依赖。但是如果有一些服务出现问题了会怎么样?
全栈程序员站长
2022/07/18
3080
spring cloud 入门系列四:使用Hystrix 实现断路器进行服务容错保护「建议收藏」
SpringCloud入门(五)-服务消费者(Feign)
Feign 是一个声明式的伪 Http 客户端,它使得写 Http 客户端变得更简单。使用 Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,Feign 支持可插拔的编码器和解码器。Feign 默认集成了 Ribbon,并和 Eureka 结合,默认实现了负载均衡的效果(所以说服务消费者一般使用Feign)
故里
2020/11/25
1.5K0
微服务精通之Feign原理解析
经过微服务精通之Ribbon原理解析的学习,我们了解到了服务消费者获取服务提供者实例的过程,都是通过RestTemplate来实现的,而且,都是模板化操作。那spring cloud是否有哪个组件可以通过注解或者配置的方式,来简化这个过程?答案是有的,就是Feign。
全栈程序员站长
2022/11/09
1.2K0
微服务精通之Feign原理解析
spring cloud 入门系列二:使用Eureka 进行服务治理「建议收藏」
服务治理可以说是微服务架构中最为核心和基础的模块,它主要用来实现各个微服务实例的自动化注册和发现。
全栈程序员站长
2022/07/18
2360
spring cloud 入门系列二:使用Eureka 进行服务治理「建议收藏」
[Spring cloud 一步步实现广告系统] 11. 使用Feign实现微服务调用
上一节我们使用了Ribbon(基于Http/Tcp)进行微服务的调用,Ribbon的调用比较简单,通过Ribbon组件对请求的服务进行拦截,通过Eureka Server 获取到服务实例的IP:Port,然后再去调用API。本节课我们使用更简单的方式来实现,使用声明式的Web服务客户端Feign,我们只需要使用Feign来声明接口,利用注解来进行配置就可以使用了,是不是很简单?实际工作中,我们也只会用到Feign来进行服务之间的调用(大多数)。接下来,我们来实例操作一把。
Isaac Zhang
2019/09/11
3550
[Spring cloud 一步步实现广告系统] 11. 使用Feign实现微服务调用
Spring Cloud中声明式服务调用Feign
前面几篇文章我们详细的介绍了Ribbon、RestTemplate、Hystrix组件,这些组件是我们Spring Cloud中非常基础的组件,小伙伴们在使用的过程中可能也发现了这些东西都是同时出现的,而且配置也都非常相似,每次开发都有很多相同的代码,因此,Spring Cloud基于Netflix Feign整合了Ribbon和Hystrix,让我们的开发工作变得更加简单,就像Spring Boot是对Spring+SpringMVC的简化一样。Spring Cloud Feign不仅在配置上大大简化了开
江南一点雨
2018/04/02
1.5K0
Spring Cloud中声明式服务调用Feign
Spring Cloud 入门教程3、服务消费者(Feign)
Feign是基于Ribbon封装的HTTP Client工具包,Feign的目标是简化HTTP Client。Feign也确实做到了这一点,使用Feign发起HTTP请求只需要定义好接口并且配置好相应的注解即可完成对对应接口的绑定。
KenTalk
2018/09/11
1.2K0
Spring Cloud 入门教程3、服务消费者(Feign)
SpringCloud的入门学习之概念理解、Feign负载均衡入门
  Feign是一个声明式WebService客户端。使用Feign能让编写Web Service客户端更加简单, 它的使用方法是定义一个接口,然后在上面添加注解,同时也支持JAX-RS标准的注解。Feign也支持可拔插式的编码器和解码器。Spring Cloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用以支持负载均衡。
别先生
2019/12/02
4850
springCloud - 第4篇 - 消费者调用服务 ( Feign )
2. spring Initializr - module SDK 选择自己的 JDK ,其余的可以不用填写,next。
微风-- 轻许--
2019/08/01
5210
Spring Cloud 2.x学习笔记:2、feign改进(Greenwich版本)
版权声明:本文为博主原创文章,欢迎转载。 https://blog.csdn.net/chengyuqiang/article/details/90712031
程裕强
2019/07/02
8550
Spring Cloud 2.x学习笔记:2、feign改进(Greenwich版本)
Spring Cloud学习-Eureka、Ribbon和Feign引子实践源码下载参考资料
看完《微服务设计》后,算是补上了自己在服务化这块的理论知识,在业界,一般有两种微服务的实践方法:基于dubbo的微服务架构、基于Spring Cloud的微服务架构。从概念上来讲,Dubbo和Spring Cloud并不能放在一起对比,因为Dubbo仅仅是一个RPC框架,实现Java程序的远程调用,实施服务化的中间件则需要自己开发;而Spring Cloud则是实施微服务的一系列套件,包括:服务注册与发现、断路器、服务状态监控、配置管理、智能路由、一次性令牌、全局锁、分布式会话管理、集群状态管理等。
阿杜
2018/08/06
9460
Spring Cloud学习-Eureka、Ribbon和Feign引子实践源码下载参考资料
SpringCloud声明式服务调用Feign
1.创建一个SpringBoot工程,这里命名为feign-consumer,然后在pom文件中添加依赖:
林老师带你学编程
2019/05/25
5130
spring cloud 入门系列六:使用Zuul 实现API网关服务「建议收藏」
通过前面几次的分享,我们了解了微服务架构的几个核心设施,通过这些组件我们可以搭建简单的微服务架构系统。比如通过Spring Cloud Eureka搭建高可用的服务注册中心并实现服务的注册和发现;
全栈程序员站长
2022/07/18
4930
spring cloud 入门系列六:使用Zuul 实现API网关服务「建议收藏」
SpringCloud之服务调用
SpringCloud的服务调用有两个东西: Ribbon是一个客户端的负载均衡器,它提供对大量的HTTP和TCP客户端的访问控制。Feign也是用的Ribbon。
用户3467126
2019/07/03
5050
SpringCloud之服务调用
Spring Cloud 组件快速入门
spring cloud 是基于 springboot 基础之上构建的一系列分布式微服务组件集,其组件主要包括:
leon_橙
2020/03/02
2K0
Spring Cloud 组件快速入门
微服务(七)——OpenFeign服务调用
官方文档:https://cloud.spring.io/spring-cloud-static/Hoxton.SR1/reference/htmlsingle/#spring-cloud-openfeign
不愿意做鱼的小鲸鱼
2022/09/26
4280
微服务(七)——OpenFeign服务调用
Spring Cloud Feign 声明式服务调用
一、Feign是什么?二、Feign的快速搭建三、Feign的几种姿态 参数绑定 继承特性四、其他配置 Ribbon 配置 Hystrix 配置
cxuan
2019/06/03
8100
SpringCloud学习笔记(3):使用Feign实现声明式服务调用
Feign是一个声明式的Web Service客户端,它简化了Web服务客户端的编写操作,相对于Ribbon+RestTemplate的方式,开发者只需通过简单的接口和注解来调用HTTP API。它支持Spring MVC注解和JAX-RS注解,还支持可插拔式的编码器和解码器。整合了Eureka,Ribbon和Hystrix,具有可插拔、基于注解、负载均衡、服务熔断等一系列便捷功能。
布禾
2020/10/29
3960
SpringCloud学习笔记(3):使用Feign实现声明式服务调用
一文带你了解服务降级的前世今生
  在分布式的环境下,多个服务之间的调用难免会出现异常、超时等问题,这些问题出现的时候,为了提高用户的体验,我们不能够直接将错误的信息展示给用户,而是在出现这种情况的时候,给用户返回一个友好的提示。服务降级的作用就在这里体现了。
IT学习日记
2022/09/13
5680
一文带你了解服务降级的前世今生
Spring Cloud中Feign的继承特性
上篇文章我们了解了Feign的基本使用,在HelloService类中声明接口时,我们发现这里的代码可以直接从服务提供者的Controller中复制过来,这些可以复制的代码Spring Cloud Feign对它进行了进一步的抽象,这里就用到了Feign的继承特性,本文我们就来看看如何利用Feign的继承特性来进一步简化我们的代码。 ---- 创建公共接口 首先我们来创建一个普通的maven工程,叫做hello-service-api,由于我们要在这一个项目中使用SpringMVC的注解,因此创建成功之后,
江南一点雨
2018/04/02
1.4K0
Spring Cloud中Feign的继承特性
推荐阅读
相关推荐
spring cloud 入门系列四:使用Hystrix 实现断路器进行服务容错保护「建议收藏」
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验