Spring Cloud入门教程-Hystrix断路器实现容错和降级
简介
Spring cloud提供了Hystrix容错库用以在服务不可用时,对配置了断路器的方法实行降级策略,临时调用备用方法。这篇文章将创建一个产品微服务,注册到eureka服务注册中心,然后我们使用web客户端访问/products
API来获取产品列表,当产品服务故障时,则调用本地备用方法,以降级但正常提供服务。
基础环境
- JDK 1.8
- Maven 3.3.9
- IntelliJ 2018.1
- Git
项目源码
添加产品服务
在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-service
cloud:
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);
}
@Bean
public 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;
@Autowired
private 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 {
@Autowired
private 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 入门教程(八): 断路器指标数据监控Hystrix Dashboard 和 Turbine
1. Hystrix Dashboard (断路器:hystrix 仪表盘) Hystrix一个很重要的功能是,可以通过HystrixCommand收集相关数据指标. Hystrix Dashboa ...
- Spring Cloud 入门教程(七): 熔断机制 -- 断路器
对断路器模式不太清楚的话,可以参看另一篇博文:断路器(Curcuit Breaker)模式,下面直接介绍Spring Cloud的断路器如何使用. SpringCloud Netflix实现了断路器库 ...
- Spring Cloud 入门教程(九): 路由网关zuul
在微服务架构中,需要几个关键的组件,服务注册与发现.服务消费.负载均衡.断路器.智能路由.配置管理等,由这几个组件可以组建一个简单的微服务架构.客户端的请求首先经过负载均衡(zuul.Ngnix),再 ...
- Spring Cloud 入门 之 Hystrix 篇(四)
原文地址:Spring Cloud 入门 之 Hystrix 篇(四) 博客地址:http://www.extlight.com 一.前言 在微服务应用中,服务存在一定的依赖关系,如果某个目标服务调用 ...
- Spring Cloud 入门教程 - 搭建配置中心服务
简介 Spring Cloud 提供了一个部署微服务的平台,包括了微服务中常见的组件:配置中心服务, API网关,断路器,服务注册与发现,分布式追溯,OAuth2,消费者驱动合约等.我们不必先知道每个 ...
- Spring Cloud 入门教程(六): 用声明式REST客户端Feign调用远端HTTP服务
首先简单解释一下什么是声明式实现? 要做一件事, 需要知道三个要素,where, what, how.即在哪里( where)用什么办法(how)做什么(what).什么时候做(when)我们纳入ho ...
- Spring Cloud 入门教程(一): 服务注册
1. 什么是Spring Cloud? Spring提供了一系列工具,可以帮助开发人员迅速搭建分布式系统中的公共组件(比如:配置管理,服务发现,断路器,智能路由,微代理,控制总线,一次性令牌,全局锁 ...
- Spring Cloud 入门教程(十):和RabbitMQ的整合 -- 消息总线Spring Cloud Netflix Bus
在本教程第三讲Spring Cloud 入门教程(三): 配置自动刷新中,通过POST方式向客户端发送/refresh请求, 可以让客户端获取到配置的最新变化.但试想一下, 在分布式系统中,如果存在很 ...
- Spring Cloud 入门教程(五): Ribbon实现客户端的负载均衡
接上节,假如我们的Hello world服务的访问量剧增,用一个服务已经无法承载, 我们可以把Hello World服务做成一个集群. 很简单,我们只需要复制Hello world服务,同时将原来的端 ...
随机推荐
- 11 PopupMenu菜单和代码例子
PopupMenu 弹出式菜单 API 11以上可用 1. 获取弹出菜单的对象 2. 在res里的menu添加菜单项 3. 将布局里的菜单项 给弹出菜单 4. 进行监听弹出菜单 5. 展示出弹出菜单 ...
- (一〇七)iPad开发之modal的切换方式与展示方式
在iPad上modal有四种切换方式,分别是竖直进入(由下到上,默认方式).水平翻转.淡入淡出. 属性要设置在将要modal出来的控制器上: /* typedef NS_ENUM(NSInteger, ...
- UNIX网络编程——非阻塞connect: Web客户程序
非阻塞的connect的实现例子出自Netscape的Web客户程序.客户先建立一个与某个Web服务器的HTTP连接,再获取一个主页.该主页往往含有多个对于其他网页的引用.客户可以使用非阻塞conne ...
- [GitHub]第二讲:GitHub客户端
文章转载自http://blog.csdn.net/loadsong/article/details/51591456 Git 是一个分布式的版本控制工具,即使我不联网,也可以在本地进行 git 的版 ...
- android:getSlotFromBufferLocked: unknown buffer: 0xf3d544c0
欢迎关注公众号,每天推送Android技术文章,二维码如下:(可扫描) 今天运行一个小程序,退出的时候竟然打出一条错误log日志.一时慌乱,在国内网站也没找到合适的答复.通过查看国外的网站终于查到了原 ...
- eclipse集成html5插件
1. 在线安装:Help->Install New Software...->Add...-> Name: "Aptana", Location: http:// ...
- Win10中virtualbox新建虚拟机不能设置64位系统解决
问题描述 在Win10中,安装virtualBox后,新建虚拟电脑时,所有的操作系统都没有64位. 解决 进入控制面板->卸载程序->启用或关闭windows功能->取消hyper- ...
- Oracle Enterprise Linux 64-bit 下Oracle11g的监听配置修改及测试步骤
测试环境:Oracle Enterprise Linux 64-bit (5.8版本) + Oracle 11g 64位 相关说明: Oracle11g64位软件的安装位置为/u01/app/orac ...
- Leetcode_8_String to Integer
本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41521063 Implement atoi to conv ...
- 基于Reactjs实现webapp(加精)
git原文链接:https://github.com/my-fe/wiki/issues/1 由于最近的reactjs实在太火,而且距离第一版已经快2年的时间了,已经相对稳定和成熟了,基于这两个前提下 ...