本文目录:


  • 一 Hystrix简介
  • 二 使用Hystrix实现容错机制
  • 三 注意事项


一、 Hystrix简介

在微服务架构中,存在很多的微服务单元,各个微服务之间通过网络进行通讯,难免出现依赖关系,若某一个单元出现故障,就很容易因依赖关系而引发故障的蔓延,产生“雪崩效应”,最终导致整个系统的瘫痪。为了解决这样的问题,产生了断路器等一系列的服务保护机制。

Hystrix是由Netflix开源的一个延迟和容错库,用于隔离访问远程系统、服务或者第三方库,防止级联失败。Hystrix具备服务降级、服务熔断、线程和信号隔离、请求缓存、请求合并以及服务监控等强大功能。

二、 使用Hystrix实现容错机制

1.在pom文件中添加spring-cloud-starter-hystrix依赖。

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

2.在启动类中添加@EnableCircuitBreaker注解,开启断路器功能(此项目也使用了Ribbon实现负载均衡)

@EnableDiscoveryClient
@SpringBootApplication
@EnableCircuitBreaker
public class EurekaClientDemoApplication {

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

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

3.配置文件,将本项目注册到Eureka中。

spring.application.name=hystrix-service
server.port=8777
eureka.client.serviceUrl.defaultZone=http://localhost:8888/eureka/

4.改造服务消费方式,新增HelloService类。使用@HystrixCommand注解指定回调方法。

@Service
public class HelloService {
    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    RestTemplate restTemplate;

    /*使用hystrix 实现容错机制,请求失败后执行Back,称之为“服务降级”*/
    @HystrixCommand(fallbackMethod = "helloBack")
    public String helloSome() {

        return this.restTemplate.getForEntity("http://string-service/hi", String.class).getBody();
    }

   //使用注解实现请求合并
    @RequestMapping(value = "/getSome", method = RequestMethod.GET)
    public String helloBack() {
        return "我是回退方法";
    }
}

4.调用该方法。

@RestController
public class ComputeController {
    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    HelloService helloService;

    //  使用ribbon 实现负载均衡
    @RequestMapping(value = "/getString", method = RequestMethod.GET)
    public String helloSome() {
        return helloService.helloSome();
    }
}

5.重新启动Eureka服务中心,和string-service的两个实例,多次访问http://localhost:8777/getString 出现负载均衡页面。

springboot项目如何降低maven版本 springboot服务降级原理_微服务


springboot项目如何降低maven版本 springboot服务降级原理_java_02


此时,我们将其中一个服务给停掉(模拟了服务出错 ),会出现如图所示结果,执行了回退逻辑,说明Hystrix生效。

springboot项目如何降低maven版本 springboot服务降级原理_断路器_03

三、 注意事项

Hyatrix默认的超时时间是2000毫秒。

执行回退逻辑并不代表断路器已经打开,请求失败、超时、被拒绝以及断路器打开都会执行回退逻辑。

Hystrix的隔离策略有两种:线程隔离(THREAD)和信号量隔离(SEMAPHORE),默认是THREAD。使用了@HystrixCommand来将某个函数包装成了Hystrix命令,这里除了定义服务降级之外,Hystrix框架就会自动的为这个函数实现调用的依赖隔离。