在消费者中加入依赖
<!--熔断器-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
在启动类中加入注解@EnableCircuitBreaker和@EnableHystrix
所以改变后的启动类在继上一篇博客后的代码如下:
package com.gaolang;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
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;
@SpringBootApplication
@EnableCircuitBreaker
@EnableFeignClients
@EnableHystrix
public class OrderMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderMain80.class,args);
}
@LoadBalanced // 使 RestTemplate 自动支持 Ribbon 负载均衡
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
而controller层的代码使用熔断器后因如下:
@Autowired
private OrderFeignClient orderFeignClient; // 注入 Feign 客户端
@PostMapping(value = "/customer/payment/create")
public CommonResult<Payment> create(Payment payment){
return orderFeignClient.create(payment);
}
@HystrixCommand(fallbackMethod = "listByHystirx",commandProperties = {
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "5"), //请求次数
}) //如果请求次数达到5次都是失败,那么直接调用listByHystirx
@GetMapping(value = "/customer/payment/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
CommonResult result = orderFeignClient.getPaymentById(id);
System.out.println("result: " + result);
return result;
}
// 修改后的回退方法
public CommonResult<Payment> listByHystirx(Long id) {
return new CommonResult<>(444, "服务端已停止服务", null);
}
因为这是单个api接口的回退方法所以
- 回退方法
listByHystirx
的参数类型必须与getPaymentById
方法完全一致,即Long id
。 - 回退方法的返回类型也必须与
getPaymentById
保持一致,即CommonResult<Payment>