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. PHP项目&RCE安全&调试&追踪&代码执行&命令执行

    常见漏洞关键字 SQL注入:select.insert.update.mysql_query.mysqli等 文件上传:$_FILES.type="file".上传.move_up ...

  2. linux的简单使用

    了解Linux的简单使用 Linux的安装 下载Linux Ubuntu版本和虚拟机VMware软件. 我已经提前下载好了,下载好的文件分享出来bd 这个是文件夹内的VMWare软件的注册码,安装完成 ...

  3. Java 封装性的小练习

    1 package com.bytezero.test2; 2 3 public class Person 4 { 5 private int age; 6 7 public void setAge( ...

  4. Java 面向对象的特征一: * 封装与隐藏

    1 * @ 面向对象的特征一: 2 * 封装与隐藏 3 * 创建一个类的对象以后,我们可以通过"对象.属性"的方式,对 4 * 对象的属性进行赋值,这里,赋值操作要受到属性的数据类 ...

  5. docsify + GitHub Page免费搭建个人博客

    docsify生成文档 docsify是一个动态生成文档网站的工具.通过编辑MarkDown文件就能实现简约清爽的文档页面. 先在Github创建项目 创建项目成功后,把项目克隆到本地(以自己的实际地 ...

  6. Pandas导出美化技巧,让你的Excel更出众

    pandas的DataFrame可以通过设置参数使得在jupyter notebook中显示的更加美观,但是,将DataFrame的数据导出excel时,却只能以默认最朴素的方式将数据写入excel. ...

  7. Prometheus组件构成及介绍

    Prometheus是一个开源的监控和告警工具包,其常用的组件主要包括以下几个部分: Prometheus Server 功能:Prometheus Server是Prometheus的核心组件,负责 ...

  8. B站Aimls的JavaFx教程目录合集

    B站里有时候不太好去找资源,用JS爬了下,整出标题和链接,方便后续查询某个知识点的使用! JavaFX视频教程第1课,hello world JavaFX视频教程第2课,application的启动方 ...

  9. day01-2-导入驱动和工具类

    满汉楼01-2 4.功能实现01 4.1导入驱动和工具类 4.1.1导入驱动 首先将连接mysql的相关jar包引入项目中,分别右键,点击add as library 4.1.2导入工具类Utilit ...

  10. Linux 使用 selenium 环境配置

    1.需要安装 Chrome 浏览器 yum install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64 ...