Spring Cloud Circuit Breaker
断路器是用来在程序中避免多层雪崩效应,能够提高程序的性能。
导入hystrix依赖
新建springboot项目,在pom文件中引入依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
初识hystrix
Spring Cloud通过hystrix来实现Circuit Breaker,通过在Service层的方法前加入注释@HystrixCommand来触发机制,触发的条件是在一定时间(属性名metrics.rollingStats.timeInMilliseconds,默认10秒)调用超过一定次数(属性名circuitBreaker.requestVolumeThreshold,默认20次)并且失败次数达到一定概率(属性名circuitBreaker.errorThresholdPercentage ,默认50%)。而失败一般是由异常或者方法超时(默认1s)触发。
TestController.java
package com.example.hystrix.service;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class TestService {
@HystrixCommand(fallbackMethod = "fallbackMethod")
public void test1(int input){
System.out.println("test1 input:"+input);
System.out.println("test1 output:"+1/input);
}
@HystrixCommand(fallbackMethod = "fallbackMethod")
public void test2(int input) throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(1500);
System.out.println("test2 "+input);
}
public void fallbackMethod(int input){
System.out.println("execute fail, the input is "+input);
}
}
fallbackMethod为熔断触发的函数。test1通过传入0来触发异常,test2通过超时触发异常。
HystrixApplication.java
一定要加EnableCircuitBreaker注释
package com.example.hystrix;
import com.example.hystrix.service.TestService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
@EnableCircuitBreaker
public class HystrixApplication {
public static void main(String[] args) throws InterruptedException {
ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(HystrixApplication.class, args);
TestService testService = configurableApplicationContext.getBean(TestService.class);
//1
testService.test1(1);
//3
testService.test1(0);
//2
testService