服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 详解Spring Cloud Hystrix断路器实现容错和降级

详解Spring Cloud Hystrix断路器实现容错和降级

2021-04-26 14:16fengqiuzhihua Java教程

本篇文章主要介绍了详解Spring Cloud Hystrix断路器实现容错和降级,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

简介

spring cloud提供了hystrix容错库用以在服务不可用时,对配置了断路器的方法实行降级策略,临时调用备用方法。这篇文章将创建一个产品微服务,注册到eureka服务注册中心,然后我们使用web客户端访问/products api来获取产品列表,当产品服务故障时,则调用本地备用方法,以降级但正常提供服务。

基础环境

  1. jdk 1.8
  2. maven 3.3.9
  3. intellij 2018.1

git:项目源码

添加产品服务

在intellij中创建一个新的maven项目,使用如下配置

  1. groupid: cn.zxuqian
  2. artifactid: productservice

然后在pom.xml中添加如下代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?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文件,添加如下内容:

?
1
2
3
4
5
6
spring:
 application:
  name: product-service
 cloud:
  config:
   uri: http://localhost:8888

在配置中心的git仓库中创建product-service.yml文件 添加如下配置并提交:

?
1
2
server:
 port: 8081

此配置指定了产品服务的端口为8081。接着创建application类,添加如下代码:

?
1
2
3
4
5
6
7
8
9
10
11
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,返回示例数据:

?
1
2
3
4
5
6
7
8
9
10
11
12
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依赖:

?
1
2
3
4
<dependency>
  <groupid>org.springframework.cloud</groupid>
  <artifactid>spring-cloud-starter-netflix-hystrix</artifactid>
</dependency>

然后更新application类的代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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类,并添加如下代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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并添加如下代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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,之后再访问同样的路径,会得到降级后的结果:夹克,毛衣

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/fengqiuzhihua/article/details/80199056

延伸 · 阅读

精彩推荐