1. 程式人生 > >Spring Cloud Hystrix 斷路器

Spring Cloud Hystrix 斷路器

autowired ping sched pack pre mage 接口 net say

1.繼承feign和ribbon

2.ribbon服務修改內容

新增依賴pom.xml:

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

3.在啟動類增加註解:@EnableHystrix

4.修改service類,增加斷路返回:

    @Service
    public class HelloService {
        @Autowired
        RestTemplate restTemplate;

        @HystrixCommand(fallbackMethod 
= "hiError") public String hiService(String name) { return restTemplate.getForObject("http://eurekaclient/hi?name="+name,String.class); } public String hiError(String name) { return "hi,"+name+",sorry,error!"; } }

5.測試,當對應的服務關閉時,訪問對應服務返回如下:

技術分享圖片

6.feign原本就繼承了斷路功能,需要在配置裏打開:

application.yml新增下面內容:

feign:
  hystrix:
      enabled: true

7.在客戶端服務接口上增加註解時,加上fallback參數即可

@FeignClient(value = "service-hi",fallback = SchedualServiceHiHystric.class)

8.然後寫這個接口的一個實現類SchedualServiceHiHystric

package com.bennytitan.servicefeign;

import org.springframework.stereotype.Component;

@Component
public class SchedualServiceHiHystric implements SchedualServiceHi { @Override public String sayHiFromClientOne(String name) { return "sorry "+name; } }

這樣就完成了。

9.如果要加入Hystrix Dashboard來打開斷路器儀表盤頁面顯示斷路器工作情況。需要增加依賴:

        <!-- 斷路器儀表盤 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
        </dependency>

10.在配置bean增加下面的bean配置:

    @Bean
    ServletRegistrationBean getServlet(){
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }

11.在服務啟動類裏添加註解:@EnableHystrixDashboard

12.測試訪問:http://localhost:8764/hystrix

打開頁面,輸入紅框內的內容後點擊按鈕技術分享圖片

技術分享圖片

完成。

Spring Cloud Hystrix 斷路器