断路器(Hystrix)

pom文件依赖

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

应用程序开启断路器

@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix  //开启断路器
public class RibbonApplication

Service添加熔断方法

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@Service
public class RibbonService {

    @Autowired
    RestTemplate restTemplate;
    
    @HystrixCommand(fallbackMethod="hiError")  //创建熔断功能并指定熔断方法
    public String ribbonService(String name) {
        return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name, String.class);
    }
    
    public String hiError(String name) {  //熔断方法
        return "hi, " + name + ", sorry, error!";
    }
}

Hystrix Dashboard

pom文件添加依赖

        <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>

应用程序开启Dashboard

import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;

@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
@EnableHystrixDashboard
public class RibbonApplication

浏览器访问http://localhost:8080/hystrix,输入http://localhost:8080/hystrix.stream点击Monitor Stream。

访问http://localhost:8080/hi?name=jack,查看监控界面。

posted @ 2018-04-26 10:29  AaronCnblogs  阅读(103)  评论(0)    收藏  举报