spring cloud笔记

来源:互联网 发布:农村淘宝佣金设置 编辑:程序博客网 时间:2024/06/06 01:07

本文仅限于个人学习用途的转载,转载请注明来自EumJi个人博客 http://www.eumji025.com/article/details/257583

Circuit Breaker

Netflix创建了hystrix库用于实现断路由监视功能,在微服务的架构中,通常是需要多级服务协调调用,才能达到最终的效果,但是在实际的使用中,很有可能发生某一个服务发生宕机的其他意外情况,此时可能会造成整个服务的阻塞,hystrix可以设置当对特定服务的呼叫达到一定阈值时(Hystrix中的默认值为5秒内的20次故障),电路打开,不进行通话。在错误和开路的情况下,开发人员可以进行抢救处理.
hystrix的fallbacl图
开放式电路会停止级联故障,并允许不必要的或失败的服务时间来愈合。回退可以是另一个Hystrix保护的调用,静态数据或一个正常的空值。回退可能被链接,所以第一个回退使得一些其他业务电话又回到静态数据。

Hystrix FallBack演示

我还是需要前面使用到的eureka server 和eureka client 来模拟微服务架构,同时我们需要新建一个项目,spring-cloud-netflix-hystrix-fallback

hystrix-fallback案例

首先我们需要引入fallback的依赖spring-cloud-starter-hystrix

pom.xml

在项目中我们还是要使用到eureka server和 eureka client和ribbon来进行实现负载功能.

        <dependency>            <groupId>org.springframework.cloud</groupId>            <artifactId>spring-cloud-starter-hystrix</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.cloud</groupId>            <artifactId>spring-cloud-starter-eureka</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>

fallbackcontroller.java

在后端的代码上还是需要用到eureka server和 eureka client,此项目依赖前面ribbon并加以补充,然后通过通过使用@HystrixCommand指定一个fallbackMethod,用于失败后的回调,具体如下

@RestControllerpublic class FallbackController {    @Autowired    private RestTemplate restTemplate;    @RequestMapping(value = "/", method = RequestMethod.GET)    @HystrixCommand(fallbackMethod = "defaultRest")    public String info() {        return restTemplate.getForEntity("http://eureka-client/", String.class).getBody();    }    public String defaultRest() {        return "default HystrixCommand";    }}

application.java

@SpringBootApplication@EnableDiscoveryClient@EnableCircuitBreaker@EnableHystrixpublic class SpringCloudNetflixHystrixApplication {    @Bean    @LoadBalanced    RestTemplate restTemplate(){        return new RestTemplate();    }    public static void main(String[] args) {        new SpringApplicationBuilder(SpringCloudNetflixHystrixApplication.class).web(true).run(args);    }}

通过@EnableDiscoveryClient发现服务,@EnableCircuitBreaker注解开启断路由的支持.

application.yml

配置文件中指明eureka服务的地址

spring:  application:    name: hystrix-fallbackserver:  port: 8083eureka:  client:    serviceUrl:     defaultZone: http://localhost:8761/eureka/

运行描述

首先开启eureka server,然后开启eureka client,最后开启hystrix fallback.
我们调用 http://localhost:8083

因为此时我们已经开启eureka client会通过ribbon的负载均衡能力去找到对应的client,所以此时会输出如下内容

hello world,this is eureka client1

然后关闭eureka service之后再次访问 http://localhost:8083
因为关闭了eureka client,此时就会发生fallback事件

default HystrixCommand

hystrix dashboard

Hystrix的主要优点之一是它收集关于每个HystrixCommand的一套指标。Hystrix仪表板以有效的方式显示每个断路器的运行状况。
使用仪表盘需要引入spring-cloud-starter-hystrix-dashboard,并使用@EnableHystrixDashboard注释您的Spring Boot主类。然后访问/hystrix,并将仪表板指向Hystrix客户端应用程序中的单个实例/hystrix.stream端点。
仪表盘的例子是基于上面我们所做的fallback demo的,将其复制一份,并命名为spring-cloud-netflix-hystrix-dashboard

pom.xml配置

基于原有的pom基础上我们还需要加上spring-cloud-starter-hystrix-dashboardspring-boot-starter-actuator
spring-boot-starter-actuator使/hystrix.stream作为管理端点。如果不追加这个依赖将会发生血的教训.当时自己在实验时候没注意到这个依赖,反复看了很久的文档才发生问题的所在,测试了很久一直出现如下的错误:
* Unable to connect to Command Metric Stream.*

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

application.java

在入口类中主要是注册一些服务,@EnableHystrixDashboard注解开启仪表盘的支持

@SpringBootApplication@EnableDiscoveryClient@EnableHystrix@EnableHystrixDashboardpublic class SpringCloudNetflixDashboardApplication {    @Bean    @LoadBalanced    RestTemplate restTemplate(){        return new RestTemplate();    }    public static void main(String[] args) {        new SpringApplicationBuilder(SpringCloudNetflixDashboardApplication.class).web(true).run(args);    }}

controller.java

将请求转发到/hystrix来开启仪表盘的配置界面,然后还是使用ribbon的方式配置负载均衡.

@Controllerpublic class DashboardController {    @RequestMapping("/")    public String home() {        return "forward:/hystrix";    }    @Autowired    private RestTemplate restTemplate;    @RequestMapping(value = "/hello", method = RequestMethod.GET)    @ResponseBody    @HystrixCommand(fallbackMethod = "defaultRest")    public String info() {        return restTemplate.getForEntity("http://eureka-client/", String.class).getBody();    }    public String defaultRest() {        return "default HystrixCommand";    }}

application.yml

在配置文件中还是简单的配置eureka的server和基本信息

spring:  application:    name: hystrix-dashboardeureka:  client:    serviceUrl:     defaultZone: http://localhost:8761/eureka/server:  port: 8084

运行描述

我们一次开启eureka server,eureka client,hystrix dashboard项目,然后访问dashboard项目的地址http://localhost:8084

我们会看到仪表盘的配置界面,然后我们进行相应的配置,设置仪表盘指向的节点.和标题超时的时间(默认2s)
hystrix dashboard配置图

设置完成后点击monitor stream,这时候仪表盘进入等待的状态,然后我们新开一个页面访问 http://localhost:8084/hello

然后再次刷新仪表盘的页面会看到如下图所示的内容.
hystrix stream显示图
当我们关闭掉eureka client的时候,此时会因为无法找到client,而发生fallback事件,刷新http://localhost:8084/hello

然后刷新仪表盘的页面会发现仪表盘记录的错误信息,其实是显示红字的1,但是截图不及时,勉强的看一下效果,如下图所示
失败的stream

我们也可以直接访问 http://localhost:8084/hystrix.stream
我们可以看到如下的相似内容

data: {"type":"HystrixCommand","name":"info","group":"DashboardController","currentTime":1494120868196,"isCircuitBreakerOpen":false,"errorPercentage":0,"errorCount":0,"requestCount":0,"rollingCountBadRequests":0,"rollingCountCollapsedRequests":0,"rollingCountEmit":0,"rollingCountExceptionsThrown":0,"rollingCountFailure":0,"rollingCountFallbackEmit":0,"rollingCountFallbackFailure":0,"rollingCountFallbackMissing":0,"rollingCountFallbackRejection":0,"rollingCountFallbackSuccess":0,"rollingCountResponsesFromCache":0,"rollingCountSemaphoreRejected":0,"rollingCountShortCircuited":0,"rollingCountSuccess":0,"rollingCountThreadPoolRejected":0,"rollingCountTimeout":0,"currentConcurrentExecutionCount":0,"rollingMaxConcurrentExecutionCount":0,"latencyExecute_mean":0,"latencyExecute":{"0":0,"25":0,"50":0,"75":0,"90":0,"95":0,"99":0,"99.5":0,"100":0},"latencyTotal_mean":0,"latencyTotal":{"0":0,"25":0,"50":0,"75":0,"90":0,"95":0,"99":0,"99.5":0,"100":0},"propertyValue_circuitBreakerRequestVolumeThreshold":20,"propertyValue_circuitBreakerSleepWindowInMilliseconds":5000,"propertyValue_circuitBreakerErrorThresholdPercentage":50,"propertyValue_circuitBreakerForceOpen":false,"propertyValue_circuitBreakerForceClosed":false,"propertyValue_circuitBreakerEnabled":true,"propertyValue_executionIsolationStrategy":"THREAD","propertyValue_executionIsolationThreadTimeoutInMilliseconds":1000,"propertyValue_executionTimeoutInMilliseconds":1000,"propertyValue_executionIsolationThreadInterruptOnTimeout":true,"propertyValue_executionIsolationThreadPoolKeyOverride":null,"propertyValue_executionIsolationSemaphoreMaxConcurrentRequests":10,"propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests":10,"propertyValue_metricsRollingStatisticalWindowInMilliseconds":10000,"propertyValue_requestCacheEnabled":true,"propertyValue_requestLogEnabled":true,"reportingHosts":1,"threadPool":"DashboardController"}data: {"type":"HystrixThreadPool","name":"DashboardController","currentTime":1494120868196,"currentActiveCount":0,"currentCompletedTaskCount":2,"currentCorePoolSize":10,"currentLargestPoolSize":2,"currentMaximumPoolSize":10,"currentPoolSize":2,"currentQueueSize":0,"currentTaskCount":2,"rollingCountThreadsExecuted":0,"rollingMaxActiveThreads":0,"rollingCountCommandRejections":0,"propertyValue_queueSizeRejectionThreshold":5,"propertyValue_metricsRollingStatisticalWindowInMilliseconds":10000,"reportingHosts":1}

这里是这些图表信息的文字内容,具体可以自行研究一下有哪些要点.

结语

本文参考spring cloud的官方文档,只是对描述比较干练的文档进行一些补充,如果想获取更好的体验,请参看

hystrix-dashboard
spring hystrix dashboard文档

与君共勉!!!

参考资料

spring-cloud官方文档
circuit_breaker文档

源码地址

hystrix-fallback
hyxtrix-dashboard
### BGM



0 0
原创粉丝点击