首页 > 技术文章 > spring cloud学习笔记四 熔断器Hystrix

daijiting 2019-07-11 14:53 原文

       我们知道分布式服务有这样一个特点,每一个微服务都有自己的业务,并且很多时候一个微服务的业务要依赖于其他微服务,如果这些相互关联的微服务中其中某个微服务请求失败时,就会导致其他调用它的微服务也会请求失败。为了避免这种情况,spring cloud为我们提供了一个熔断器Hystrix来管理。

一、Hystrix的熔断

  Hystrix的熔断主要是为我们解决“雪崩效应”,它的作用主要是针对我们所调用的接口,如果接口请求异常,那么Hystrix会熔断到一个方法中。

  1.导入maven  

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.4.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
            <version>1.4.0.RELEASE</version>
        </dependency>

  2.在启动类中加入@EnableCircuitBreaker注解。 

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class DemoHystrixApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoHystrixApplication .class, args);
    }


}

  3.创建controller层,controller层中对访问接口进行了熔断

@RestController
public class DemoHystrixController {


   @Autowired
    DemoHystrixService demoHystrixService ;

    //请求熔断注解,当服务出现问题时候会执行fallbackMetho属性的名为fallCode的方法
    @HystrixCommand(fallbackMethod = "fallCode")
  @RequestMapping("/show")
    public String hystrixMain(@PathVariable("num") int num) {
        String str=demoHystrixService.show(num);
      if(str==null)//如果没有找的数据,就报一个异常,Hystrix会熔断调用fallCode方法
      throw new RuntimeException("数据不存在") ;
              }
    }

  private String fallCode() {      
        return "数据不存在";
    } 


}

二、服务降级

  在分布式项目中,某个服务的并发过高,导致资源不够用了,此时可以考虑关闭一些服务来提供资源。关闭的服务程序不会报异常,而是本地的调用操作,这就是服务降级。服务的降级处理是在客户端实现的,与你的服务器端没有关系。

  1.创建一个controller层 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.java.feign.service.HostService;

@RestController
public class DowngradeController {

    @Autowired
    DemoHystrixService demoHystrixService;

    @RequestMapping("/down")
    public JSONObject getDown(@PathVariable("nums") int nums) {

        return demoHystrixService.showJsonData(nums);
    }
}

  2.创建一个服务降级管理类,实现FallbackFactory接口,FallbackFactory中的泛型就是我们需要降级的controller 

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import feign.hystrix.FallbackFactory;

@Component
public class DowngradeFallbackFactory implements FallbackFactory<DowngradeController > {

    @Override
    public DowngradeController create(Throwable cause) {
        return new DowngradeController () {

            @Override
            public JSONObject getDown(int nums) {
                JSONObject json = new JSONObject();
                json.put("num", num);
                json.put("message", "服务的降级处理");
                return json;
            }
        };
    }

}

 

 

 

 

 

 

 

 

推荐阅读