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. CentOS8安装与配置jdk1.8 与远程分发复制jdk到另一个虚拟机

    安装配置JDK 一.卸载系统自带的OpenJDK及相关的java文件 1.查看系统自带OpenJDK版本 命令介绍: 2.卸载java 命令介绍: 二.下载安装jdk 1.命令式安装 查看JDK软件包 ...

  2. 微信小程序开发:页面分享卡片、风格选择、通道启用等可配置

    上文说到,我们部署了定时任务,但是有个地方忘记在上文写了,这里补上,就是定时任务的超时时间问题,超时时间有7200秒: 我们改成7100秒: 再把云函数调用的云对象的超时时间也改下: 超时时间多一点, ...

  3. JavaScript 最新动态:2024 年新功能

    前言 随着 Web 技术的日新月异,JavaScript 也在不断地吸收新的特性和技术,以满足日益复杂和多样化的开发需求.在 2024 年,JavaScript 迎来了一系列令人瞩目的新功能,这些功能 ...

  4. Set-Alias navi ./navi.bat - 设置别名 - powershell入门 (后期改方案了,换npm script)

    需求 开机要启动好几个服务,原先都用vscode启动,觉得可能比较占内存,所以改成命令行 发现直接运行bat,需要输入./batName.bat 一次还行,天天输入就麻烦了 命令 Set-Alias ...

  5. 火柴 基于everything的搜索软件 软件推荐 Ctrl+Ctrl 显示 tab转换 本机搜索和网络搜索

    https://www.huochaipro.com/

  6. python计算二进制bin文件hash值

    一 hash的价值 hash值的唯一性仅仅在是同一个文件的情况下得到了同样的hash值,而哪怕错误一个字节也会得到不一样的hash值. hash值得最大价值就是唯一性.这样在bin文件检查和校验这块用 ...

  7. electron程序运行在某些 windows 上白屏

    现象: 打包后的 electron 程序 运行在某些 windows 上白屏 项目情况: vue3.0  项目使用 vue-cli 创建 使用 vue add electron-builder 添加打 ...

  8. c语言随笔

    c语言随笔 整型数据类型 unsigned int [signed] int [signed] short [int] unsigned long long [int] // long long 为c ...

  9. day14--Java常用类之字符串相关类02

    Java常用类 2.字符串相关类 String.StringBuilder.StringBuffer类是三个字符串相关类. String类代表不可变字符序列,StringBuilder类和String ...

  10. day32-JQuery05

    jQuery05 9.作业 9.1homework01 对多选框进行操作,输出选中的多选框的个数,并且把选中爱好的名称显示. <!DOCTYPE html> <html lang=& ...