当前位置: 首页 > news >正文

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-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时再作说明。br/>使用`@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/

转载于:https://blog.51cto.com/13727459/2112841

相关文章:

  • 0505 php-数组、控制语句、函数
  • 第三期 行为规划——6.输出状态转换方程的量
  • Ping程序
  • 群发功能推广通知短信的一些问题
  • 蓝海存储开关机注意事项总结
  • Fragment向父Activity传值
  • jmeter学习笔记
  • 债券和股票
  • 使用Vagrant 在Virtual Box 上安装Docker--(补充九步构建自己的hello world Docker镜像)
  • Linux下PHP5.2安装curl扩展支持https
  • 分布式架构总汇【转】
  • MFS分布式文件系统部署
  • 阿里云Elasticsearch公测发布
  • Django中Model-Form验证
  • win10 常用设置 桌面出来计算机图标,固定桌面摆好的图标设置方法,电脑设备ID方法...
  • android 一些 utils
  • Angular 2 DI - IoC DI - 1
  • es的写入过程
  • EventListener原理
  • Flannel解读
  • JavaScript设计模式与开发实践系列之策略模式
  • linux学习笔记
  • SOFAMosn配置模型
  • spring boot 整合mybatis 无法输出sql的问题
  • 前言-如何学习区块链
  • 如何利用MongoDB打造TOP榜小程序
  • 如何抓住下一波零售风口?看RPA玩转零售自动化
  • 带你开发类似Pokemon Go的AR游戏
  • ​软考-高级-信息系统项目管理师教程 第四版【第19章-配置与变更管理-思维导图】​
  • !!java web学习笔记(一到五)
  • # centos7下FFmpeg环境部署记录
  • # 学号 2017-2018-20172309 《程序设计与数据结构》实验三报告
  • #gStore-weekly | gStore最新版本1.0之三角形计数函数的使用
  • #预处理和函数的对比以及条件编译
  • (C#)Windows Shell 外壳编程系列4 - 上下文菜单(iContextMenu)(二)嵌入菜单和执行命令...
  • (c语言版)滑动窗口 给定一个字符串,只包含字母和数字,按要求找出字符串中的最长(连续)子串的长度
  • (javascript)再说document.body.scrollTop的使用问题
  • (k8s中)docker netty OOM问题记录
  • (二)WCF的Binding模型
  • (附源码)springboot 校园学生兼职系统 毕业设计 742122
  • (亲测成功)在centos7.5上安装kvm,通过VNC远程连接并创建多台ubuntu虚拟机(ubuntu server版本)...
  • (全注解开发)学习Spring-MVC的第三天
  • (三)centos7案例实战—vmware虚拟机硬盘挂载与卸载
  • (十八)devops持续集成开发——使用docker安装部署jenkins流水线服务
  • (转)IOS中获取各种文件的目录路径的方法
  • (转)淘淘商城系列——使用Spring来管理Redis单机版和集群版
  • (轉)JSON.stringify 语法实例讲解
  • .[backups@airmail.cc].faust勒索病毒的最新威胁:如何恢复您的数据?
  • .NET Reactor简单使用教程
  • .Net 路由处理厉害了
  • .NET 使用 ILMerge 合并多个程序集,避免引入额外的依赖
  • @html.ActionLink的几种参数格式
  • @javax.ws.rs Webservice注解
  • [22]. 括号生成
  • [acwing周赛复盘] 第 94 场周赛20230311