代码例子下载:https://download.csdn.net/download/spark_guo/10501108
在微服务架构中存在那么多的服务单位。若一个单元出现故障就很容易因依赖关系而引发故障的蔓延,最终导致整个系统的瘫痪,这样的架构相较传统架构更加不稳定。为了解决这样的问题,产生了断路器等一系列的服务保护机制。
在分布式架构中,断路器模式的作用也是类似的,当某个服务单元发生故障之后通过断路器的故障监控,类似熔断保险丝向调用方返回一个错误响应,而不是长时间的等待,这样就不会使得线程因调用故障服务才会长时间占用不释放,避免故障在分布式系统中的蔓延。
Spring cloud Hystrx实现断路器、线程隔离等一系列服务保护功能。它也是基于Netflix断开源框架Hystrix实现断,该框架的目标在于通过控制那些访问远程系统、服务和第三方库的节点,从而对延迟和故障提供更强大断容错能力。Hystrix具备服务降级、服务熔断、线程和信号隔离、请求换成、请求合并以及服务监控等强大功能。
搭建测试例子:
1、pom.xml引入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
2、客户端,主要启动类上加上@EnableCircuitBreaker注解,开启断路器功能;
@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication
{
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main( String[] args )
{
SpringApplication.run(ConsumerApplication.class, args);
}
}
3、在服务方法上加上@HystrixCommand(fallbackMethod="helloFallback")注解,指定回调方法。
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod="helloFallback")
public String helloService(){
long start = System.currentTimeMillis();
String result = restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class).getBody();
System.out.println("cost:"+(System.currentTimeMillis() -start));
return result;
}
public String helloFallback(){
return "error";
}
}
4、服务端测试:
@RestController
public class HelloController
{
private final Logger logger = Logger.getLogger(getClass());
@Autowired
private DiscoveryClient client;
@RequestMapping(value="/hello", method = RequestMethod.GET)
public String index() throws Exception
{
ServiceInstance serviceInstance = client.getLocalServiceInstance();
// 让处理线程等待几秒钟
int sleepTime = new Random().nextInt(3000);
logger.info("sleepTime:"+sleepTime);
Thread.sleep(sleepTime);
logger.info("/hello, host:" + serviceInstance.getHost() +", service_id:"+serviceInstance.getServiceId());
String result = "Hello World!";
System.out.println(result);
return result;
}
}