spring cloud--------------------HystrixCommand使用


一。注解使用:
(一)注解同步執行
1.注解開啟斷路器功能 @EnableCircuitBreaker
2.方法事例
@HystrixCommand(fallbackMethod = "erro")
public String succese(){
Person person=new Person();
person.setAddress("beijing");
person.setAge(18);
person.setName("zzq");
return restTemplate.postForObject("http://hello-service/hello-post",person,String.class);
}
注意: fallbackMethod:請求失敗的情況下調用的方法
public String erro(){
return "404-----------405";
}
(二)異步執行
1.在項目的入口類中配置一個HystrixCommandAspect的Bean,如下:

@Bean
public HystrixCommandAspect hystrixCommandAspect() {
return new HystrixCommandAspect();
}
2. 方法事例:@HystrixCommand(fallbackMethod = "erro")
public Future<String> succeseYibu(){
return new AsyncResult<String>() {
@Override
public String invoke() {
Person person=new Person();
person.setAddress("beijing");
person.setAge(18);
person.setName("zzq");
return restTemplate.postForObject("http://hello-service/yanshi",person,String.class);
}
};
}
3.controller調用方法

@RequestMapping("/xiaofeizhe-duanlu-HystrixCommandYibu")
public String HystrixCommandYibu() throws ExecutionException, InterruptedException {
Future<String> stringFuture = helloService.succeseYibu();
System.out.println("HystrixCommandYibu---------異步調用方法---------");
String s = stringFuture.get();
System.out.println(s);
return s;
}
二。繼承HystrixCommand類使用
1.class類事例
public class PersonCommand extends HystrixCommand<String> {
private RestTemplate restTemplate;
private Long id;
public PersonCommand(Setter setter, RestTemplate restTemplate,Long id) {
super(setter);
this.restTemplate=restTemplate;
this.id=id;
}

@Override
protected String run() throws Exception {
return restTemplate.getForObject("http://hello-service/yanshi",String.class);
}

@Override
protected String getFallback() {
return "HystrixCommand<String> 返回失敗";
}
}
備注:run()方法設計執行的方法 ,getFallback()調用run失敗執行的方法
2.controller使用展示
(1)同步執行
@RequestMapping("/xiaofeizhe-tongbu")
public String agin(){
PersonCommand myfirstHy = new PersonCommand(HystrixCommand.Setter.withGroupKey(
HystrixCommandGroupKey.Factory.asKey("myfirstHy")).andCommandPropertiesDefaults(
HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(2000)), restTemplate(), 1l);
return myfirstHy.execute();
}
(2)異步執行
execute()方法變成queue()方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM