前言
hystrix是netflix开源的服务熔断组件,在Spring Cloud中整合进来,形成Spring Cloud的熔断降级体系。服务降级主要是为了服务雪崩,造成下游的服务不可用,可用性是分布式服务的必须要求。
1. ribbon服务
在上一章的ribbon服务,仅需添加netflix的组件,加入注解即可,下面来改造ribbon-consumer项目,熔断是服务调用方执行。
pom修改,加入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
要开启服务,需要在main类上注上@EnableHystrix
package com.spring.cloud.ribbon.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
@EnableDiscoveryClient
@SpringBootApplication
@EnableHystrix
public class RibbonConsumerMain {
public static void main(String[] args) {
SpringApplication.run(RibbonConsumerMain.class, args);
}
}
同样,熔断后需要如何处理,需要调用方写处理逻辑。需要在服务方法上加上@HystrixCommand注解
package com.spring.cloud.ribbon.consumer.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;
import java.util.HashMap;
import java.util.Map;
@Service
public class ConsumerService {
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "consumerMarkError")
public Map consumerMark() {
return restTemplate.getForObject("http://RIBBON-SERVICE/mark",Map.class);
}
@HystrixCommand(defaultFallback = "consumerMarkError")
public Map consumerMark2() {
return restTemplate.getForObject("http://RIBBON-SERVICE/mark",Map.class);
}
public Map consumerMarkError() {
Map<String, String> map = new HashMap<>();
map.put("error", "service is not used");
return map;
}
}
设置熔断后处理逻辑,可设置默认fallback。访问http://localhost:8205/consumer/,服务正常。
当我们停掉8203端口,spring.profiles=r2的服务出现熔断
再次刷新,由于ribbon轮训服务又可以访问,下次刷新,又出现熔断
总结
服务熔断是Spring Cloud集成netflix的hystrix模块实现的,并用ribbon项目做实现,但这样会很麻烦,这两种功能都需要配置,Spring Cloud为了处理这些不方便,将这两种常用的功能集成进来,就是feign。