1.使用原因
在微服务架构中,根据业务来拆分成一个个的服务,服务与服务之间可以相互调用(RPC),在Spring Cloud可以用RestTemplate+Ribbon和Feign来调用。为了保证其高可用,单个服务通常会集群部署。由于网络原因或者自身的原因,服务并不能保证100%可用,如果单个服务出现问题,调用这个服务就会出现线程阻塞,此时若有大量的请求涌入,Servlet容器的线程资源会被消耗完毕,导致服务瘫痪。服务与服务之间的依赖性,故障会传播,会对整个微服务系统造成灾难性的严重后果,这就是服务故障的“雪崩”效应。
准备
导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在启动类上加上@EnableHystrix注解开启断路器
package com.example.serviceribbon;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix//开启断路器
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceRibbonApplication.class, args);
}
//开启负载均衡
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
package com.example.serviceribbon.service;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/**
* @Auther: TG
* @Date: 2018/7/17 0017 15:06
* @Description:
*/
@Service
public class RibbonService {
@Autowired
private RestTemplate restTemplate;
//发生故障回调方法
@HystrixCommand(fallbackMethod = "getMessageError")
public String getMessage(){
return restTemplate.getForObject("http://service-hi/hi",String.class);
}
//回调方法
public String getMessageError(){
return "error for waring";
}
}
先正常启动注册中心、服务提供者、服务消费者
调用service-hi服务、此实现采用RestTemplate
正常返回
关闭service-hi服务
再次调用service-hi服务
在Feign当中断路器是存在的只需要在yml文件当中开启
feign.hystrix.enabled=true