zoukankan      html  css  js  c++  java
  • 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()方法
  • 相关阅读:
    性能测试工具LoadRunner19-LR之Controller IP欺骗
    JavaScript—06数组与函数
    JavaScript—05流程控制与代码规范要求
    JavaScript—04运算符
    JS做简单的留言板
    JavaScript—03 变量与数据类型
    JavaScript—02 JS组成及注释等
    JavaScript—01汇编语言和计算机基础脑图
    01移动端布局基础-脑图
    解决粘包-复杂版
  • 原文地址:https://www.cnblogs.com/anxbb/p/9848740.html
Copyright © 2011-2022 走看看