Spring Cloud之旅(四) -- 断路器

前言

由于网络原因或者自身的原因,服务并不能保证100%可用,如果单个服务出现问题,调用这个服务就会出现线程阻塞,此时若有大量的请求涌入,Servlet容器的线程资源会被消耗完毕,导致服务瘫痪。服务与服务之间的依赖性,故障会传播,会对整个微服务系统造成灾难性的严重后果,这就是服务故障的“雪崩”效应。

为了解决这个问题,业界提出了断路器模型。

开始创建

pom.xml

Feign自带了断路器,而RestTemplate+Ribbon没自带断路器,需额外引入依赖


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

application.yml

Feign自带的断路器需在配置文件中开启

feign:
    hystrix:
        enabled: true

Feign的断路器实现

Feign的断路器实现是增加一个断路器的实现类

IHelloService

package com.asiainfo.aigov.consumer_feign.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.asiainfo.aigov.consumer_feign.service.impl.HelloServiceHystrix;

@FeignClient(name="eureka-client",fallback=HelloServiceHystrix.class)
public interface IHelloService {

    @RequestMapping("/hello")
    String hello(@RequestParam("name") String name);
    
}

HelloServiceHystrix

package com.asiainfo.aigov.consumer_feign.service.impl;

import org.springframework.stereotype.Service;

import com.asiainfo.aigov.consumer_feign.service.IHelloService;

@Service
public class HelloServiceHystrix implements IHelloService {

    @Override
    public String hello(String name) {
        return "invoke hello error! name -> " + name;
    }

}

RestTemplate+Ribbon的断路器实现

@HystrixCommand(fallbackMethod = "helloError")
@RequestMapping("/hello2")
public String hello2(String name) {
    return restTemplate.getForObject("http://eureka-client/hello?name="+name, String.class);
}
    
public String helloError(String name) {
    return "invoke hello error! name -> " + name;
}

RestTemplate+Ribbon开启断路器功能

package com.asiainfo.aigov.consumer_feign;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableHystrix
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class ConsumerFeignApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerFeignApplication.class, args);
    }
    
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    
}

总结

断路器开启后,如果服务不可用,将快速返回失败,从而防止“雪崩”效应。

你可能感兴趣的:(Spring Cloud之旅(四) -- 断路器)