Spring Cloud OpenFeign:基于Ribbon和Hystrix的声明式服务调用

  • SpringCloud学习教程
  • SpringCloud

Spring Cloud OpenFeign 是声明式的服务调用工具,它整合了Ribbon和Hystrix,拥有负载均衡和服务容错功能,本文将对其用法进行详细介绍。

#Feign简介

Feign是声明式的服务调用工具,我们只需创建一个接口并用注解的方式来配置它,就可以实现对某个服务接口的调用,简化了直接使用RestTemplate来调用服务接口的开发量。Feign具备可插拔的注解支持,同时支持Feign注解、JAX-RS注解及SpringMvc注解。当使用Feign时,Spring Cloud集成了Ribbon和Eureka以提供负载均衡的服务调用及基于Hystrix的服务容错保护功能。

#创建一个feign-service模块

这里我们创建一个feign-service模块来演示feign的常用功能。

#在pom.xml中添加相关依赖

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

#在application.yml中进行配置

server:
port: 8701
spring:
application:
name: feign-service
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8001/eureka/

#在启动类上添加@EnableFeignClients注解来启用Feign的客户端功能

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignServiceApplication { public static void main(String[] args) {
SpringApplication.run(FeignServiceApplication.class, args);
} }

#添加UserService接口完成对user-service服务的接口绑定

我们通过@FeignClient注解实现了一个Feign客户端,其中的value为user-service表示这是对user-service服务的接口调用客户端。我们可以回想下user-service中的UserController,只需将其改为接口,保留原来的SpringMvc注释即可。

/**
* Created by macro on 2019/9/5.
*/
@FeignClient(value = "user-service")
public interface UserService {
@PostMapping("/user/create")
CommonResult create(@RequestBody User user); @GetMapping("/user/{id}")
CommonResult<User> getUser(@PathVariable Long id); @GetMapping("/user/getByUsername")
CommonResult<User> getByUsername(@RequestParam String username); @PostMapping("/user/update")
CommonResult update(@RequestBody User user); @PostMapping("/user/delete/{id}")
CommonResult delete(@PathVariable Long id);
}

#添加UserFeignController调用UserService实现服务调用

/**
* Created by macro on 2019/8/29.
*/
@RestController
@RequestMapping("/user")
public class UserFeignController {
@Autowired
private UserService userService; @GetMapping("/{id}")
public CommonResult getUser(@PathVariable Long id) {
return userService.getUser(id);
} @GetMapping("/getByUsername")
public CommonResult getByUsername(@RequestParam String username) {
return userService.getByUsername(username);
} @PostMapping("/create")
public CommonResult create(@RequestBody User user) {
return userService.create(user);
} @PostMapping("/update")
public CommonResult update(@RequestBody User user) {
return userService.update(user);
} @PostMapping("/delete/{id}")
public CommonResult delete(@PathVariable Long id) {
return userService.delete(id);
}
}

#负载均衡功能演示

  • 启动eureka-service,两个user-service,feign-service服务,启动后注册中心显示如下:

2019-10-04 15:15:34.829  INFO 9236 --- [nio-8201-exec-5] c.macro.cloud.controller.UserController  : 根据id获取用户信息,用户名称为:macro
2019-10-04 15:15:35.492 INFO 9236 --- [io-8201-exec-10] c.macro.cloud.controller.UserController : 根据id获取用户信息,用户名称为:macro
2019-10-04 15:15:35.825 INFO 9236 --- [nio-8201-exec-9] c.macro.cloud.controller.UserController : 根据id获取用户信息,用户名称为:macro

#Feign中的服务降级

Feign中的服务降级使用起来非常方便,只需要为Feign客户端定义的接口添加一个服务降级处理的实现类即可,下面我们为UserService接口添加一个服务降级实现类。

#添加服务降级实现类UserFallbackService

需要注意的是它实现了UserService接口,并且对接口中的每个实现方法进行了服务降级逻辑的实现。

/**
* Created by macro on 2019/9/5.
*/
@Component
public class UserFallbackService implements UserService {
@Override
public CommonResult create(User user) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser);
} @Override
public CommonResult<User> getUser(Long id) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser);
} @Override
public CommonResult<User> getByUsername(String username) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser);
} @Override
public CommonResult update(User user) {
return new CommonResult("调用失败,服务被降级",500);
} @Override
public CommonResult delete(Long id) {
return new CommonResult("调用失败,服务被降级",500);
}
}

#修改UserService接口,设置服务降级处理类为UserFallbackService

修改@FeignClient注解中的参数,设置fallback为UserFallbackService.class即可。

@FeignClient(value = "user-service",fallback = UserFallbackService.class)
public interface UserService {
}

#修改application.yml,开启Hystrix功能

feign:
hystrix:
enabled: true #在Feign中开启Hystrix

#服务降级功能演示

#日志打印功能

Feign提供了日志打印功能,我们可以通过配置来调整日志级别,从而了解Feign中Http请求的细节。

#日志级别

  • NONE:默认的,不显示任何日志;
  • BASIC:仅记录请求方法、URL、响应状态码及执行时间;
  • HEADERS:除了BASIC中定义的信息之外,还有请求和响应的头信息;
  • FULL:除了HEADERS中定义的信息之外,还有请求和响应的正文及元数据。

#通过配置开启更为详细的日志

我们通过java配置来使Feign打印最详细的Http请求日志信息。

/**
* Created by macro on 2019/9/5.
*/
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}

#在application.yml中配置需要开启日志的Feign客户端

配置UserService的日志级别为debug。

logging:
level:
com.macro.cloud.service.UserService: debug

#查看日志

调用http://localhost:8701/user/1open in new window进行测试,可以看到以下日志。

2019-10-04 15:44:03.248 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService      : [UserService#getUser] ---> GET http://user-service/user/1 HTTP/1.1
2019-10-04 15:44:03.248 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser] ---> END HTTP (0-byte body)
2019-10-04 15:44:03.257 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser] <--- HTTP/1.1 200 (9ms)
2019-10-04 15:44:03.257 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser] content-type: application/json;charset=UTF-8
2019-10-04 15:44:03.258 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser] date: Fri, 04 Oct 2019 07:44:03 GMT
2019-10-04 15:44:03.258 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser] transfer-encoding: chunked
2019-10-04 15:44:03.258 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser]
2019-10-04 15:44:03.258 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser] {"data":{"id":1,"username":"macro","password":"123456"},"message":"操作成功","code":200}
2019-10-04 15:44:03.258 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser] <--- END HTTP (92-byte body)

#Feign的常用配置

#Feign自己的配置

feign:
hystrix:
enabled: true #在Feign中开启Hystrix
compression:
request:
enabled: false #是否对请求进行GZIP压缩
mime-types: text/xml,application/xml,application/json #指定压缩的请求数据类型
min-request-size: 2048 #超过该大小的请求会被压缩
response:
enabled: false #是否对响应进行GZIP压缩
logging:
level: #修改日志级别
com.macro.cloud.service.UserService: debug

#Feign中的Ribbon配置

在Feign中配置Ribbon可以直接使用Ribbon的配置,具体可以参考Spring Cloud Ribbon:负载均衡的服务调用open in new window

#Feign中的Hystrix配置

在Feign中配置Hystrix可以直接使用Hystrix的配置,具体可以参考Spring Cloud Hystrix:服务容错保护open in new window

#使用到的模块

springcloud-learning
├── eureka-server -- eureka注册中心
├── user-service -- 提供User对象CRUD接口的服务
└── feign-service -- feign服务调用测试服务

Spring Cloud OpenFeign:基于Ribbon和Hystrix的声明式服务调用的更多相关文章

  1. spring cloud 系列第4篇 —— feign 声明式服务调用 (F版本)

    源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 一.feign 简介 在上一个用例中,我们使用ribbon+restTem ...

  2. Spring Cloud Eureka 分布式开发之服务注册中心、负载均衡、声明式服务调用实现

    介绍 本示例主要介绍 Spring Cloud 系列中的 Eureka,使你能快速上手负载均衡.声明式服务.服务注册中心等 Eureka Server Eureka 是 Netflix 的子模块,它是 ...

  3. Spring Cloud Feign 声明式服务调用

    目录 一.Feign是什么? 二.Feign的快速搭建 三.Feign的几种姿态 参数绑定 继承特性 四.其他配置 Ribbon 配置 Hystrix 配置 一.Feign是什么? ​ 通过对前面Sp ...

  4. Spring Cloud Feign声明式服务调用(转载)+遇到的问题

    转载:原文 总结: 1.pom添加依赖 2.application中填写正确的eureka配置 3.启动项中增加注解 @EnableFeignClients 4.填写正确的调用接口 通过原文使用Fei ...

  5. Spring Cloud 2-Feign 声明式服务调用(三)

    Spring Cloud Feign  1. pom.xml 2. application.yml 3. Application.java 4. Client.java 简化RestTemplate调 ...

  6. 声明式服务调用:Spring Cloud Feign

    最近在学习Spring Cloud的知识,现将声明式服务调用:Spring Cloud Feign 的相关知识笔记整理如下.[采用 oneNote格式排版]

  7. Spring Cloud 声明式服务调用 Feign

    一.简介 在上一篇中,我们介绍注册中心Eureka,但是没有服务注册和服务调用,服务注册和服务调用本来应该在上一章就应该给出例子的,但是我觉得还是和Feign一起讲比较好,因为在实际项目中,都是使用声 ...

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

    一.Spring Cloud Feign概念引入通过前面的随笔,我们了解如何通过Spring Cloud ribbon进行负责均衡,如何通过Spring Cloud Hystrix进行服务断路保护,两 ...

  9. Spring Cloud第七篇 | 声明式服务调用Feign

    本文是Spring Cloud专栏的第七篇文章,了解前六篇文章内容有助于更好的理解本文: Spring Cloud第一篇 | Spring Cloud前言及其常用组件介绍概览 Spring Cloud ...

  10. 第六章 声明式服务调用: Spring Cloud Feign

    我们在使用 Spring Cloud Ribbon 时, 通常都会利用它对 RestTemplate 的请求拦截来实现对依赖服务的接口调用, 而 RestTemplate 已经实现了对 HTTP 请求 ...

随机推荐

  1. 为Oracle链接服务器使用分布式事务

    1 现象 在SQL Server中创建指向Oracle的链接服务器,SQL语句在事务中向链接服务器插入数据.返回链接服务器无法启动分布式事务的报错. 2 解决 在Windows平台下,SQL Serv ...

  2. C++ //类模板对象做函数参数 //三种方式 //1.指定传入的类型 --直接显示对象的数据类型 //2.参数模板化 --将对象中的参数变为模板进行传递 //3.整个类模板化 --将这个对象类型 模板化进行传递

    1 //类模板对象做函数参数 2 //三种方式 3 //1.指定传入的类型 --直接显示对象的数据类型 4 //2.参数模板化 --将对象中的参数变为模板进行传递 5 //3.整个类模板化 --将这个 ...

  3. 摆脱鼠标系列 - vscode - ctrl+up 光标上移动4行 ctrl+down 光标下移4行

    为什么 摆脱鼠标系列 - vscode - ctrl+up 光标上移动4行 之前滚动屏幕总是用鼠标,现在改为 ctrl + 上箭头或下箭头 实现起来稍微有些麻烦 实现 需要安装 macros 插件 这 ...

  4. FastGithub.UI64位中文版V2.1.4绿色版 - 软件推荐

    推荐理由 相对于改hosts,这个更好用 FastGithub.UI64位中文版V2.1.4绿色版 https://www.cr173.com/soft/670733.html

  5. K8s中Labels(标签)和Annotations(注解)对比

    在Kubernetes中,Labels(标签)和Annotations(注解)都是用于为资源对象添加元数据的机制,但它们在用途.选择能力以及数据形式上存在一些关键的区别. 首先,Labels主要用于标 ...

  6. Ubuntu 14.04 升级到Gnome3.12z的折腾之旅(警示后来者)+推荐Extensions.-------(二)

    PS:要转载请注明出处,本人版权所有. PS: 这个只是基于<我自己>的理解, 如果和你的原则及想法相冲突,请谅解,勿喷. 前置说明   本文发布于 2014-12-22 15:33:35 ...

  7. 大年学习linux(第三节---用户管理)

    三.用户管理 用户和用户组操作命令 ld Finger Pwck 检查/etc/passwd配置文件内的信息与实际主文件夹是否存在,还可比较/etc/passwd和/etc/shadow的信息是否一致 ...

  8. WPF异步命令以及SqlSugar异步增删改查

    1.异步 /// <summary> /// 查询全部 /// </summary> /// <returns></returns> public as ...

  9. 一款比Typora更简洁优雅的Markdown编辑器神器(完全开源免费)

    前言 自从Typora收费以后经常有朋友会问有没有一个好用.简洁.免费的Markdown编辑器推荐的,今天大姚给大家分享一款比Typora更简洁优雅的.完全开源免费(MIT License)Markd ...

  10. spark和hadoop的区别

    hadoopHadoop是一个由Apache基金会所开发的分布式系统基础架构. 用户可以在不了解分布式底层细节的情况下,开发分布式程序.充分利用集群的威力进行高速运算和存储. Hadoop实现了一个分 ...