正文
修改依赖
复制
spring-cloud-ribbon-consumer
项目,修改名称为
spring-cloud-ribbon-consumer-hystrix
在项目
pom.xml
中引入需要的依赖内容:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
开启服务注册
在程序的启动类
RibbonConsumerApplication
通过
@EnableHystrix
开启 Hystrix 断路器监控
package io.ymq.example.ribbon.consumer.hystrix;
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.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableHystrix
@EnableDiscoveryClient
@SpringBootApplication
public class RibbonConsumerApplication {
@LoadBalanced
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonConsumerApplication.class, args);
}
}
消费提供者方法
修改
ConsumerController
类的,
hello
方法,加上注解
@HystrixCommand(fallbackMethod = "defaultStores")
该注解对该方法创建了熔断器的功能
,并指定了
defaultStores
熔断方法,熔断方法直接返回了一个字符串,
"feign + hystrix ,提供者服务挂了"
@HystrixCommand 表明该方法为hystrix包裹,可以对依赖服务进行隔离、降级、快速失败、快速重试等等hystrix相关功能
该注解属性较多,下面讲解其中几个
-
fallbackMethod 降级方法
-
commandProperties 普通配置属性,可以配置HystrixCommand对应属性,例如采用线程池还是信号量隔离、熔断器熔断规则等等
-
ignoreExceptions 忽略的异常,默认HystrixBadRequestException不计入失败
-
groupKey() 组名称,默认使用类名称
-
commandKey 命令名称,默认使用方法名
package io.ymq.example.ribbon.consumer.hystrix;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "defaultStores")
@GetMapping(value = "/hello")
public String hello() {
return restTemplate.getForEntity("http://eureka-provider/"