Spring Cloud实战(五)-Spring Cloud Netflix Hystrix

概要

  • 什么是Spring Cloud Netflix Hystrix?

  • 怎么用 Spring Cloud Netflix Hystrix?

  • Hystrix常见配置介绍

什么是Spring Cloud Netflix Hystrix?

Spring Cloud Netflix Hystrix是分布式系统处理超时和错误的机制,如下图所示,分布式系统中某个用户请求依赖A,H,I,P服务.
图片描述
当此请求并发超过50的时候,服务I处理速度变慢,但是服务I还是被调用.
图片描述
图片描述
大量请求会阻塞在Tomcat服务器上,影响其它整个服务.在复杂的分布式架构的应用程序有很多的依赖,都会不可避免地在某些时候失败.高并发的依赖失败时如果没有隔离措施,当前应用服务就有被拖垮的风险.
Spring Cloud Netflix Hystrix就是隔离措施的一种实现,可以设置在某种超时或者失败情形下断开依赖调用或者返回指定逻辑,从而提高分布式系统的稳定性.

怎么用Spring Cloud Netflix Hystrix?

百说不如一run,构造一个例子来实现,例子要实现使用Hystrix的Fallback(失败后)逻辑来处理错误情景
1.Eureka Server,和Eureka Client跟之前一样,只需改造Eureka Sentence
2.Eureka Sentence 添加pom依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
        </dependency>

3.Eureka Sentence的Application添加hystrix注解

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableHystrix
@EnableHystrixDashboard
public class ApplicationSentence {
    public static void main(String[] args) {
        SpringApplication.run(ApplicationSentence.class, args);
    }
}

4.Eureka Sentence WordServiceImpl在subject,adjective,noun上添加HystrixCommand注解并实现相应的fallback逻辑.

@Service
public class WordServiceImpl implements WordService {

    @Autowired
    VerbClient verbClient;
    @Autowired
    SubjectClient subjectClient;
    @Autowired
    ArticleClient articleClient;
    @Autowired
    AdjectiveClient adjectiveClient;
    @Autowired
    NounClient nounClient;
   

    @Override
    @HystrixCommand(fallbackMethod="getFallbackSubject")
    public String getSubject() {
        return subjectClient.getWord();
    }



    @Override
    public String getVerb() {
        return verbClient.getWord();
    }

    @Override
    public String getArticle() {
        return articleClient.getWord();
    }

    @Override
    @HystrixCommand(fallbackMethod="getFallbackAdjective")
    public String getAdjective() {
        return adjectiveClient.getWord();
    }

 
    @HystrixCommand(fallbackMethod="getFallbackNoun")
    public String getNoun() {
        return nounClient.getWord();
    }

    public String getFallbackSubject() {
        return "某人";
    }

    public String getFallbackAdjective() {
        return "";
    }

    public String getFallbackNoun() {
        return "某物";
    }
}

5.依次启动Eureka Server,Eureka Client,Eureka Sentence,这个跟之前一样造句,停掉subject,noun服务,可以看到其可以走fallback逻辑.
6.使用异步和reactive形式的Hystrix,修改getSubject()为Future,修改getNoun()为Observable.SentenceServiceImpl也做相应的修改.

@Service
public class WordServiceImpl implements WordService {

    @Autowired
    VerbClient verbClient;
    @Autowired
    SubjectClient subjectClient;
    @Autowired
    ArticleClient articleClient;
    @Autowired
    AdjectiveClient adjectiveClient;
    @Autowired
    NounClient nounClient;
    @Override
    @HystrixCommand(fallbackMethod = "getFallbackSubject")
    public Future<String> getSubject() {
        return new AsyncResult<String>() {
            @Override
            public String invoke() {
                return subjectClient.getWord();
            }
        };
    }

//    @Override
//    @HystrixCommand(fallbackMethod="getFallbackSubject")
//    public String getSubject() {
//        return subjectClient.getWord();
//    }



    @Override
    public String getVerb() {
        return verbClient.getWord();
    }

    @Override
    public String getArticle() {
        return articleClient.getWord();
    }

    @Override
    @HystrixCommand(fallbackMethod="getFallbackAdjective")
    public String getAdjective() {
        return adjectiveClient.getWord();
    }

    @Override
    @HystrixCommand(fallbackMethod="getFallbackNoun")
    public Observable<String> getNoun() {
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> observer) {
                try {
                    if (!observer.isUnsubscribed()) {
                        observer.onNext(nounClient.getWord());
                        observer.onCompleted();
                    }
                } catch (Exception e) {
                    observer.onError(e);
                }
            }
        });
    }
//    @HystrixCommand(fallbackMethod="getFallbackNoun")
//    public String getNoun() {
//        return nounClient.getWord();
//    }

    public String getFallbackSubject() {
        return "某人";
    }

    public String getFallbackAdjective() {
        return "";
    }

    public String getFallbackNoun() {
        return "某物";
    }
}

SentenceServiceImpl修改成下面

@Service
public class SentenceServiceImpl implements SentenceService {

    @Autowired WordService wordService;


    /**
     * Assemble a sentence by gathering random words of each part of speech:
     */
    public String buildSentence() {

        final List<String> nounList = Lists.newArrayList();
        wordService.getNoun().subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {
                nounList.add(s);
            }
        });

        try {
            return String.format("%s %s %s %s %s.", wordService.getSubject().get(), wordService.getVerb(),
                    wordService.getArticle(), wordService.getAdjective(), nounList.get(0));
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return "error";
    }

}

7.查看Hystrix dashboard可以看到方法调用的统计信息
访问http://127.0.0.1:8020/hystrix并输入http://127.0.0.1:8020/hystrix...可以查看Hystrix接口调用信息
图片描述


mumubin
375 声望185 粉丝