资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

SpringCloudHystrix断路器如何实现容错和降级-创新互联

小编给大家分享一下Spring Cloud Hystrix断路器如何实现容错和降级,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

鸡冠ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18982081108(备注:SSL证书合作)期待与您的合作!

基础环境

  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中添加如下代码:



  4.0.0

  cn.zxuqian
  productService
  1.0-SNAPSHOT
  
    org.springframework.boot
    spring-boot-starter-parent
    2.0.1.RELEASE
    
  

  
    UTF-8
    1.8
  

  
    
      org.springframework.cloud
      spring-cloud-starter-netflix-eureka-client
    
    
      org.springframework.cloud
      spring-cloud-starter-config
    
    
      org.springframework.boot
      spring-boot-starter-web
    

    
      org.springframework.boot
      spring-boot-starter-test
      test
    
  
  
    
      
        org.springframework.cloud
        spring-cloud-dependencies
        Finchley.M9
        pom
        import
      
    
  

  
    
      
        org.springframework.boot
        spring-boot-maven-plugin
      
    
  

  
    
      spring-milestones
      Spring Milestones
      https://repo.spring.io/libs-milestone
      
        false
      
    
  

我们继续使用了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依赖:


  org.springframework.cloud
  spring-cloud-starter-netflix-hystrix

然后更新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 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,之后再访问同样的路径,会得到降级后的结果:夹克,毛衣

以上是“Spring Cloud Hystrix断路器如何实现容错和降级”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!


本文名称:SpringCloudHystrix断路器如何实现容错和降级-创新互联
文章来源:http://cdkjz.cn/article/doheci.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220