zoukankan      html  css  js  c++  java
  • 读书笔记——spring cloud 中 HystrixCommand的四种执行方式简述

    读了《Spring Cloud 微服务实战》第151-154页, 总结如下:

    Hystrix存在两种Command,一种是HystrixCommand,另一种是HystrixObservableCommand。

    对于HystrixCommand,有四种执行方式:

    1、同步执行:execute,同步,直接返回结果,该方式有注解方式的实现

        @HystrixCommand
    public String helloService(){ return restTemplate.getForEntity("http://hello-service/hello",String.class).getBody(); }

    2、异步执行:queue,异步,返回Future,直到调用Future的get方法时,才会阻塞,直获取结果,在那之前都是在异步执行的,该方式有注解方式的实现

        @HystrixCommand
    public Future<String> queueService(){ return new AsyncResult<String>(){ public String invoke(){ return restTemplate.getForEntity("http://hello-service/hello",String.class).getBody(); } }; }

    以上两种,返回值不同,注意观察。

    3、异步执行,直到订阅时发射返回结果:observe该方式未找到注解方式的实现

    4、同步执行,直到订阅才开始执行,然后发射返回结果:toObservable该方式未找到注解方式的实现

    以上3和4,因为只能发射一次,所以不如使用HystrixObservableCommand,可以发射多次,并且有注解方式的实现,可替代上方

    1、HystrixObservableCommand的 observe 和  toObservable

        @HystrixCommand(fallbackMethod = "helloFallback",
                observableExecutionMode = ObservableExecutionMode.EAGER//observe方式
                /*,observableExecutionMode = ObservableExecutionMode.LAZY toObservable方式*/
                /*,ignoreExceptions = {Exception.class} 定义忽略异常,则遇到该类异常将不再执行fallback方法,直接包装后抛出*/
                )
        //用的是注解写的是HystrixCommand,其实实现的是HystrixObservableCommand,因此支持自定义多次发射
        public Observable<String> obserableService(){
            return Observable.create(new Observable.OnSubscribe<String>(){
               public void call(Subscriber<? super String> observer){
                   try{
                //这里不需加判断,可以删掉判断
    if(!observer.isUnsubscribed()){ String result = restTemplate.getForEntity("http://hello-service/hello",String.class).getBody(); observer.onNext(result); //可以写多个onNext,发射多次 observer.onNext(result); observer.onCompleted(); } }catch (Exception e){ observer.onError(e); } } }); //在方法外边调用subscribe方法 }

    所谓“发射”,大家可以理解为 使用回调方法,发射多次,意味着可以多次调用回调方法,比如:

    1、如果返回了一个List,我们又想把List里的每个对象都处理一下

    2、再或者我们的实现里调用了多个服务,可以每个服务的结果都处理一下

    等。。。

  • 相关阅读:
    [转载]windows进程中的内存结构
    RTTI和4个强制转换运算符
    由于应用程序配置不正确,程序未能启动
    光照
    服务器数据同步
    SAP
    PHP输入流php://input
    五款常用mysql slow log分析工具的比较
    开发搜索引擎–PHP中文分词
    大型网站调试工具之一(php性能优化分析工具XDebug)
  • 原文地址:https://www.cnblogs.com/flying607/p/8387175.html
Copyright © 2011-2022 走看看