前言
由于網(wǎng)絡(luò)原因或者自身的原因,服務(wù)并不能保證100%可用,如果單個(gè)服務(wù)出現(xiàn)問題,調(diào)用這個(gè)服務(wù)就會(huì)出現(xiàn)線程阻塞,此時(shí)若有大量的請(qǐng)求涌入,Servlet容器的線程資源會(huì)被消耗完畢,導(dǎo)致服務(wù)癱瘓。服務(wù)與服務(wù)之間的依賴性,故障會(huì)傳播,會(huì)對(duì)整個(gè)微服務(wù)系統(tǒng)造成災(zāi)難性的嚴(yán)重后果,這就是服務(wù)故障的“雪崩”效應(yīng)。
為了解決這個(gè)問題,業(yè)界提出了斷路器模型。
開始創(chuàng)建
pom.xml
Feign自帶了斷路器,而RestTemplate+Ribbon沒自帶斷路器,需額外引入依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
application.yml
Feign自帶的斷路器需在配置文件中開啟
feign:
hystrix:
enabled: true
Feign的斷路器實(shí)現(xiàn)
Feign的斷路器實(shí)現(xiàn)是增加一個(gè)斷路器的實(shí)現(xiàn)類
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的斷路器實(shí)現(xiàn)
@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();
}
}
總結(jié)
斷路器開啟后,如果服務(wù)不可用,將快速返回失敗,從而防止“雪崩”效應(yīng)。