Spring Cloud入门教程-Hystrix断路器实现容错和降级
简介
Spring cloud提供了Hystrix容错库用以在服务不可用时,对配置了断路器的方法实行降级策略,临时调用备用方法。这篇文章将创建一个产品微服务,注册到eureka服务注册中心,然后我们使用web客户端访问/products
API来获取产品列表,当产品服务故障时,则调用本地备用方法,以降级但正常提供服务。
基础环境
- JDK 1.8
- Maven 3.3.9
- IntelliJ 2018.1
- Git
项目源码
Gitee码云
添加产品服务
在intelliJ中创建一个新的maven项目,使用如下配置
- groupId: cn.zxuqian
- artifactId: productService
然后在pom.xml中添加如下代码:
<?xml version="1.0" encoding="UTF-8"?>
<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>cn.zxuqian</groupId><artifactId>productService</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.1.RELEASE</version><relativePath/></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><java.version>1.8</java.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-config</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>Finchley.M9</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><repositories><repository><id>spring-milestones</id><name>Spring Milestones</name><url>https://repo.spring.io/libs-milestone</url><snapshots><enabled>false</enabled></snapshots></repository></repositories></project>
我们继续使用了spring-cloud-starter-netflix-eureka-client
以使产品服务自动注册到eureka服务中。然后还使用了spring-cloud-starter-config
读取配置服务中心的配置文件。这个项目只是一个简单的spring web项目。
在src/main/resources
下创建bootstrap.yml
文件,添加如下内容:
spring:application:name: product-servicecloud:config:uri: http://localhost:8888
在配置中心的git仓库中创建product-service.yml
文件 添加如下配置并提交:
server:port: 8081
此配置指定了产品服务的端口为8081。接着创建Application
类,添加如下代码:
package cn.zxuqian;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@EnableDiscoveryClient
@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
@EnableDiscoveryClient
注解将指示spring cloud自动把本服务注册到eureka。最后创建cn.zxuqian.controllers.ProductController
控制器,提供/products
API,返回示例数据:
package cn.zxuqian.controllers;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class ProductController {@RequestMapping("/products")public String productList() {return "外套,夹克,毛衣,T恤";}
}
配置Web客户端
打开我们之前创建的web
项目,在pom.xml
中新添Hystrix
依赖:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
然后更新Application
类的代码:
package cn.zxuqian;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}@Beanpublic RestTemplate rest(RestTemplateBuilder builder) {return builder.build();}
}
这里使用@EnableCircuitBreaker
来开启断路器功能,然后还添加了一个rest
方法并使用@Bean
注解。这部分属于Spring依赖注入功能,使用@Bean
标记的方法将告诉如何初始化此类对象,比如本例中就是使用RestTemplateBuilder
来创建一个RestTemplate
的对象,这个稍后在使用断路器的service中用到。
创建cn.zxuqian.service.ProductService
类,并添加如下代码:
package cn.zxuqian.services;import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;import java.util.List;@Service
public class ProductService {private final RestTemplate restTemplate;@Autowiredprivate DiscoveryClient discoveryClient;public ProductService(RestTemplate restTemplate) {this.restTemplate = restTemplate;}@HystrixCommand(fallbackMethod = "backupProductList")public String productList() {List<ServiceInstance> instances = this.discoveryClient.getInstances("product-service");if(instances != null && instances.size() > 0) {return this.restTemplate.getForObject(instances.get(0).getUri() + "/products", String.class);}return "";}public String backupProductList() {return "夹克,毛衣";}
}
之所以要创建一个Service类,是因为Hystrix只能在标记为@Service
或@Component
的类中使用,这样才能够正常使用Spring Context所提供的API。这个以后深入Spring时再作说明。
使用@HystrixCommand
注解后,Hystrix将监控被注解的方法即productList
(底层使用proxy包装此方法以此实现监控),一旦此方法的错误累积到一定门槛的时候,就会启动断路器,后续所有调用productList
方法的请求都会失败,而会临时调用fallbackMethod
指定的方法backupProductList()
,然后当服务恢复正常时,断路器就会关闭。
我们还在此类中用了DiscoveryClient
用以寻找产品服务的uri地址,使用产品服务的spring.application.name
配置项的值,即product-service
作为serviceID
传给discoveryClient.getInstances()
方法,然后会返回一个list,因为目前我们只有一个产品服务启动着,所以只需要取第一个实例的uri地址即可。
然后我们使用RestTemplate
来访问产品服务的api,注意这里使用了Spring的构造方法注入,即之前我们用@Bean
注解的方法会被用来初始化restTemplate
变量,不需我们手动初始化。RestTemplate
类提供了getForObject()
方法来访问其它Rest API并把结果包装成对象的形式,第一个参数是要访问的api的uri地址,第二参数为获取的结果的类型,这里我们返回的是String,所以传给他String.class
。
backupProductList()
方法返回了降级后的产品列表信息。
最后创建一个控制器cn.zxuqian.controllers.ProductController
并添加如下代码:
package cn.zxuqian.controllers;import cn.zxuqian.services.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class ProductController {@Autowiredprivate ProductService productService;@RequestMapping("/products")public String productList() {return productService.productList();}
}
这里使用ProductService
为/products
路径提供数据。
测试
首先,我们使用spring-boot:run
插件启动配置中心服务,config-server,然后启动eureka-server,再启动product-service,最后启动web客户端,稍等片刻待eureka服务注册成功之后访问http://localhost:8080/products
,正常的情况下会得到外套,夹克,毛衣,T恤
结果,然后我们关闭product-service,之后再访问同样的路径,会得到降级后的结果:夹克,毛衣
欢迎访问我的博客http://zxuqian.cn/spring-cloud-tutorial-hystrix/
Spring Cloud入门教程-Hystrix断路器实现容错和降级相关推荐
- Spring Cloud入门教程(二):客户端负载均衡(Ribbon)
对于大型应用系统负载均衡(LB:Load Balancing)是首要被解决一个问题.在微服务之前LB方案主要是集中式负载均衡方案,在服务消费者和服务提供者之间又一个独立的LB,LB通常是专门的硬件,如 ...
- Spring Cloud 入门 之 Hystrix 篇(四)
一.前言 在微服务应用中,服务存在一定的依赖关系,如果某个目标服务调用慢或者有大量超时造成服务不可用,间接导致其他的依赖服务不可用,最严重的可能会阻塞整条依赖链,最终导致业务系统崩溃(又称雪崩效应). ...
- Spring Cloud 入门教程(二): 配置管理
使用Config Server,您可以在所有环境中管理应用程序的外部属性.客户端和服务器上的概念映射与Spring Environment和PropertySource抽象相同,因此它们与Spring ...
- Spring Cloud入门教程 - Zuul实现API网关和请求过滤
简介 Zuul是Spring Cloud提供的api网关和过滤组件,它提供如下功能: 认证 过滤 压力测试 Canary测试 动态路由 服务迁移 负载均衡 安全 静态请求处理 动态流量管理 在本教程中 ...
- Spring Cloud 入门 之 Zuul 篇(五)
一.前言 随着业务的扩展,微服务会不对增加,相应的其对外开放的 API 接口也势必增多,这不利于前端的调用以及不同场景下数据的返回,因此,我们通常都需要设计一个 API 网关作为一个统一的 API 入 ...
- 微服务理念与Spring Cloud入门-----父工程与API子工程的创建教程
前言 随着软件工程的规模的迅速扩大,对响应的速度的要求的越来越高,软件的开发过程面临越来越大的挑战.为了提高开发的效率,和质量,以及对成本的压缩,对软件的模块化,以及希望像硬件模块一样,能即插即用,成 ...
- 【夯实Spring Cloud】Spring Cloud中使用Hystrix实现断路器原理详解(上)
本文属于[夯实Spring Cloud]系列文章,该系列旨在用通俗易懂的语言,带大家了解和学习Spring Cloud技术,希望能给读者带来一些干货.系列目录如下: [夯实Spring Cloud]D ...
- Spring Cloud基础教程
Spring Cloud基础教程 2017-04-04 被围观 90375 次 该教程内容不定时更新,如您对这些内容感兴趣,可以关注我的博客或微信公众号! 本教程示例代码: GitHub:https ...
- Spring Cloud入门,看这篇就够了!
点击▲关注 "中生代技术" 给公众号标星置顶 更多精彩 第一时间直达 概述 首先我给大家看一张图,如果大家对这张图有些地方不太理解的话,我希望你们看完我这篇文章会恍然大悟. 什 ...
最新文章
- Codeforces Gym 100342J Problem J. Triatrip 求三元环的数量 bitset
- 当yum 遇到No more mirrors to try
- AI:2020年6月21日北京智源大会演讲分享之09:20-09:40黄铁军教授《智源进展报告》
- 1.8-1.10 大数据仓库的数据收集架构及监控日志目录日志数据,实时抽取之hdfs系统上...
- CRM呼叫中心里的Java stack
- WPF ComboBox 使用 ResourceBinding 动态绑定资源键并支持语言切换
- jar各个版本号的意义
- 大厂的 SDK 写法,偷学到了!
- 关于Fedora8中DNS配置问题解决
- LeetCode 98 验证二叉搜索树
- 小米路由器3无线网连接到服务器,小米路由器3设置完成后,手机能用,电脑没法上网...
- mysql 求平方_如何用MySQL求一个范围内的完全平方数
- autojs识别数字ocr
- JS简单获取猫眼电影所有城市完整的json数据(包括城市id和城市拼音)
- 墨卡托投影参数设置_[转载]MRT投影参数设置及原理
- 冯乐乐之一 图形学基础 Shader入门精要
- 计算机网络连接限制,网络连接受限,详细教您网络连接受限怎么解决
- GitHub上的AutoML
- 百度飞桨ai达人创造营01-创意的诞生
- 放大后字体变形的一点思考