熔斷器的概念和優(yōu)點(diǎn)參考 springcloud(四):熔斷器Hystrix, 講的很詳細(xì)
基于feign的Hystrix
在前面的feign的消費(fèi)者的項(xiàng)目上面改改就ok
- application.properties中添加 feign.hystrix.enabled=true, 開啟服務(wù)熔斷
- 編寫helloService接口的實(shí)現(xiàn)類HelloServiceFallBack
@Service
public class HelloServiceFallBack implements HelloService {
@Override
public String hello(Map<String, String> map) {
// 可以進(jìn)行一些錯(cuò)誤記錄, 將未完成的業(yè)務(wù)可能人工干預(yù)處理
return ">>>>>>>>>>>>>調(diào)用服務(wù)失敗, 參數(shù):"+map.toString();
}
}
- 在helloService的注解FeignClient中添加fallback = HelloServiceFallBack.class, 表示調(diào)用服務(wù)異常后回調(diào)執(zhí)行HelloServiceFallBack的業(yè)務(wù)
@FeignClient(value ="spring-cloud-eureka-producer",fallback = HelloServiceFallBack.class) - 服務(wù)生產(chǎn)者的代碼中拋一個(gè)異常
@RestController
public class ApiHello {
/*@Autowired
private LoadBalancerClient loadBalancerClient;*/
@RequestMapping(value = "/hello")
public String sayHello(HttpServletRequest request) throws IllegalAccessException {
String name = request.getParameter("name");
String age = request.getParameter("age");
if(age.equals("23")){
throw new IllegalAccessException("我出錯(cuò)了xox");
}
System.out.println("我是9000");
return JSON.toJSONString("hello,"+name);
}
}
- 啟動(dòng)消費(fèi)者和服務(wù)者, 請(qǐng)求參數(shù)中加入age參數(shù), 發(fā)現(xiàn)age=23的時(shí)候, 消費(fèi)者回調(diào)了HelloServiceFallBack的業(yè)務(wù)
基于Ribbon的Hystrix
在ribbon的consumer上修改
- 新增依賴spring-cloud-starter-netflix-hystrix
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
- 啟動(dòng)類上添加注解 @EnableHystrix
- controller中加入fallback
@RequestMapping(value = "/consumer/hello")
@HystrixCommand(fallbackMethod = "fallBackre")
public String hello(HttpServletRequest request) throws JsonProcessingException {
String name = request.getParameter("name");
String age = request.getParameter("age");
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("name",name);
map.add("age",age);
return this.restTemplate.postForObject("http://spring-cloud-eureka-producer/hello",map,String.class);
}
/**
* 服務(wù)異潮蹋回調(diào)方法
* @return
*/
public String fallBackre(HttpServletRequest request){
String name = request.getParameter("name");
return ">>>>>>>>>>>>>調(diào)用服務(wù)失敗, 參數(shù):"+name;
}
這是方法級(jí)別的回調(diào), 注意方法參數(shù)值
- 完畢, 啟動(dòng)服務(wù)者個(gè)消費(fèi)者, 當(dāng)age=23時(shí), 調(diào)用fallBackre方法
over