06.Spring Cloud OpenFeign:基于Ribbon和Hystrix的声明式服务调用
Spring Cloud OpenFeign:基于Ribbon和Hystrix的声明式服务调用
Feign简介
Feign是声明式的服务调用工具,我们只需创建一个接口并用注解的方式来配置它,就可以实现对某个服务接口的调用,简化了直接使用RestTemplate来调用服务接口的开发量。Feign具备可插拔的注解支持,同时支持Feign注解、JAX-RS注解及SpringMvc注解。当使用Feign时,Spring Cloud集成了Ribbon和Eureka以提供负载均衡的服务调用及基于Hystrix的服务容错保护功能。
创建一个feign-service模块
pom中添加依赖
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.6.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><modelVersion>4.0.0</modelVersion><artifactId>feign-service</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><spring-cloud.version>Greenwich.SR2</spring-cloud.version></properties><dependencies><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><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring-cloud.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
application.yml
server:port: 7701
spring:application:name: feign-service
eureka:client:register-with-eureka: truefetch-registry: trueservice-url:defaultZone: http://localhost:7001/eureka/
feign:hystrix:enabled: true #在Feign中开启Hystrix
logging:level:com.dnydys.service.UserService: debug
注解来启用Feign的客户端功能
在启动类上添加@EnableFeignClients来启用Feign的客户端功能
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignServiceApplication {public static void main(String[] args) {SpringApplication.run(FeignServiceApplication.class, args);}}
添加UserService接口完成对user-service服务的接口绑定
/*** @author dnydys* @description * @updateTime 2022/1/23
*/
@FeignClient(value = "user-service",fallback = UserFallbackService.class)
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实现服务调用
/*** @author dnydys* @description* @updateTime 2022/1/23
*/
@RestController
@RequestMapping("/user")
public class UserFeignController {@Autowiredprivate 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(SpringCloud中一套代码启动两个服务(修改端口号即可)),feign-service服务,启动后注册中心显示如下:
多次调用http://localhost:7701/user/1进行测试,可以发现运行在7201和7202的user-service服务交替打印如下信息:
添加服务降级实现类UserFallbackService
注意: 它实现了UserService接口,并且对接口中的每个实现方法进行了服务降级逻辑的实现。
/*** @author dnydys* @description * @updateTime 2022/1/23
*/
@Component
public class UserFallbackService implements UserService {@Overridepublic CommonResult create(User user) {User defaultUser = new User(-1L, "defaultUser", "123456");return new CommonResult<>(defaultUser);}@Overridepublic CommonResult<User> getUser(Long id) {User defaultUser = new User(-1L, "defaultUser", "123456");return new CommonResult<>(defaultUser);}@Overridepublic CommonResult<User> getByUsername(String username) {User defaultUser = new User(-1L, "defaultUser", "123456");return new CommonResult<>(defaultUser);}@Overridepublic CommonResult update(User user) {return new CommonResult("调用失败,服务被降级",500);}@Overridepublic CommonResult delete(Long id) {return new CommonResult("调用失败,服务被降级",500);}
}
在yml中添加配置
feign:hystrix:enabled: true #在Feign中开启Hystrix
服务降级功能演示
关闭两个user-service服务,重新启动feign-service
调用http://localhost:7701/user/1进行测试,可以发现返回了服务降级信息
日志打印功能
Feign提供了日志打印功能,我们可以通过配置来调整日志级别,从而了解Feign中Http请求的细节。
日志级别
- NONE:默认的,不显示任何日志;
- BASIC:仅记录请求方法、URL、响应状态码及执行时间;
- HEADERS:除了BASIC中定义的信息之外,还有请求和响应的头信息;
- FULL:除了HEADERS中定义的信息之外,还有请求和响应的正文及元数据。
通过配置开启日志
/*** @author dnydys* @description* @updateTime 2022/1/23
*/
@Configuration
public class FeignConfig {@BeanLogger.Level feignLoggerLevel() {return Logger.Level.FULL;}
}
在yml中添加配置
logging:level:com.dnydys.service.UserService: debug
查看日志
调用http://localhost:7701/user/1进行测试,可以看到以下日志。
2022-02-07 22:13:35.592 DEBUG 6572 --- [-user-service-1] com.dnydys.service.UserService : [UserService#getUser] <--- HTTP/1.1 200 (322ms)
2022-02-07 22:13:35.592 DEBUG 6572 --- [-user-service-1] com.dnydys.service.UserService : [UserService#getUser] content-type: application/json;charset=UTF-8
2022-02-07 22:13:35.592 DEBUG 6572 --- [-user-service-1] com.dnydys.service.UserService : [UserService#getUser] date: Mon, 07 Feb 2022 14:13:35 GMT
2022-02-07 22:13:35.592 DEBUG 6572 --- [-user-service-1] com.dnydys.service.UserService : [UserService#getUser] transfer-encoding: chunked
2022-02-07 22:13:35.592 DEBUG 6572 --- [-user-service-1] com.dnydys.service.UserService : [UserService#getUser]
2022-02-07 22:13:35.593 DEBUG 6572 --- [-user-service-1] com.dnydys.service.UserService : [UserService#getUser] {"data":{"id":1,"username":"admin","password":"admin"},"message":"操作成功","code":200}
2022-02-07 22:13:35.594 DEBUG 6572 --- [-user-service-1] com.dnydys.service.UserService : [UserService#getUser] <--- END HTTP (91-byte body)
2022-02-07 22:13:36.437 INFO 6572 --- [erListUpdater-0] c.netflix.config.ChainedDynamicProperty : Flipping property: user-service.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
Feign的常用配置
Feign自己的配置
feign:hystrix:enabled: true #在Feign中开启Hystrixcompression:request:enabled: false #是否对请求进行GZIP压缩mime-types: text/xml,application/xml,application/json #指定压缩的请求数据类型min-request-size: 2048 #超过该大小的请求会被压缩response:enabled: false #是否对响应进行GZIP压缩
logging:level: #修改日志级别com.dnydys.service.UserService: debug
Feign中的Ribbon配置
在Feign中配置Ribbon可以直接使用Ribbon的配置,具体可以参考Spring Cloud Ribbon:负载均衡的服务调用
Feign中的Hystrix配置
在Feign中配置Hystrix可以直接使用Hystrix的配置,具体可以参考Spring Cloud Hystrix:服务容错保护
代码地址
github:https://github.com/DNYDYS/SpringClouddDemo.git
06.Spring Cloud OpenFeign:基于Ribbon和Hystrix的声明式服务调用相关推荐
- Spring Cloud Feign 1(声明式服务调用Feign 简介)
Spring Cloud Feign基于Netflix Feign 同时整合了Spring Cloud Ribbon和Spring Cloud Hytrix,除了提供两者的强大功能外,它还提供了一种声 ...
- 04.声明式服务调用:Spring Cloud Feign(Greenwich.SR2)
1.Feign是什么 Feign是整合了Ribbon与Hystrix外,还提供了声明式的Web服务客户端定义方式.采用了声明式API接口的风格,将Java Http客户端绑定到它的内部.Feign的首 ...
- 实践出真知之Spring Cloud之基于Eureka、Ribbon、Feign的真实案例
转载自 实践出真知之Spring Cloud之基于Eureka.Ribbon.Feign的真实案例 Eureka是Spring Cloud Eureka的简称,是Netflix提供的组件之一.通过E ...
- Spring Cloud Alibaba - 10 Ribbon 自定义负载均衡策略(权重算法)
文章目录 Pre 工程 首先屏蔽细粒度配置 然后通过代码设置一个全局配置 指定 GlobalRibbonConfig GlobalRibbonConfig 设置负载均衡策略 开发自定义策略 (权重访问 ...
- Spring Cloud(5)---基于 Spring Cloud 完整的微服务架构实战
基于 Spring Cloud 完整的微服务架构实战 技术栈 Spring boot - 微服务的入门级微框架,用来简化 Spring 应用的初始搭建以及开发过程. Eureka - 云端服务发现,一 ...
- 几种常见的微服务架构方案简述——ZeroC IceGrid、Spring Cloud、基于消息队列
微服务架构是当前很热门的一个概念,它不是凭空产生的,是技术发展的必然结果.虽然微服务架构没有公认的技术标准和规范草案,但业界已经有一些很有影响力的开源微服务架构平台,架构师可以根据公司的技术实力并结合 ...
- Spring Cloud教程 第七弹 spring cloud openfeign
更多Spring与微服务相关的教程请戳这里 Spring与微服务教程合集 1.概述 1.1.Feign是什么 feign是一个声明式的web service客户端,它使得编写web service客户 ...
- Spring Cloud OpenFeign 接口反序列化失效,该怎么解决?
点击关注公众号,实用技术文章及时了解 来源:blog.csdn.net/qq_34347620/article/ details/124295302 1. 关于 Spring Boot 无侵入式API ...
- Spring Cloud OpenFeign - - - > 契约配置
项目源代码:https://download.csdn.net/download/weixin_42950079/87177425 Feign 是 Netflix 公司开发的声明式 HTTP 客户端, ...
- Spring Cloud OpenFeign 是什么?
本文内容如有错误.不足之处,欢迎技术爱好者们一同探讨,在本文下面讨论区留言,感谢. 文章目录 简述 使用 依赖关系 结论 参考资料 简述 Spring Cloud OpenFeign 用于 Sprin ...
最新文章
- 用ECMAScript4 ( ActionScript3) 实现Unity的热更新 -- 使用原型链和EventTrigger
- mysql集群安装配置
- 游戏服务器哪个系统困难些,游戏服务器哪个系统困难些
- 【Ubuntu】ubuntu系统下python3和python2环境自由切换
- js模块化编程之彻底弄懂CommonJS和AMD/CMD!
- 虚拟机无法接受组播消息_基于UDP的组播通信
- Displaying a Refresh Control for Table Views
- Padrino 生成器指南
- git原理详解与实操指南_全网最精:学git一套就够了,从入门到原理深度剖析
- script 标签中引用asp文件不显示的原因
- WinAircrackPack无线破解
- “微肥”还是“歪fai”
- 【AAD】单独停止某一个用户账号AD与AAD之间的同步
- 你不可不用的十类Mac装机必备软件
- 苹果手机能有软件测试硬件是否给更换过,爱思助手等第三方软件检测靠谱吗?果粉必须了解!...
- 希尔排序Linux下c 实现
- Iphone, Ipad, Iwatch 屏蔽系统更新提示
- Docker删除镜像/容器
- 港科夜闻|香港科技大学史维校长及汪扬副校长出席“一流大学建设系列研讨会--2021”暨中国大学校长联谊会线上会议...
- P2P DHT sp