一、熔斷簡單案例
在user-consumer中添加依賴:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
啟動類上加注解:
@EnableHystrix
@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class UserConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(UserConsumerApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}
}
在需要熔斷的調用遠端服務的方法上添加注解:
@HystrixCommand
,并添加熔斷時的處理邏輯。當有很多的方法需要熔斷時,可以在類上加注解
@DefaultProperties(defaultFallback = "fallBackMethod")
來指定一個類的全局熔斷方法。
@Component
//@DefaultProperties(defaultFallback = "fallBackMethod")
public class UserDao {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@HystrixCommand(fallbackMethod = "findUserByIdFallback")
public User findUserById(Integer id) {
long begin = System.currentTimeMillis();
User user = this.restTemplate.getForObject("http://user-service/user/findUser/" + id, User.class);
long end = System.currentTimeMillis();
// 記錄通路用時:
System.out.println("查詢用時:" + (end - begin) + "ms");
return user;
}
//熔斷處理邏輯
public User findUserByIdFallback(Integer id) {
User user = new User();
user.setId(id);
user.setName("使用者資訊查詢出現錯誤");
return user;
}
}
修改服務提供者的方法,模拟通路異常:
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User findUserById(Integer id){
try {
Thread.sleep(new Random().nextInt(2000));
} catch (InterruptedException e) {
e.printStackTrace();
}
return this.userMapper.selectByPrimaryKey(id);
}
}
通過浏覽器通路:

二、熔斷時間的配置
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMillisecond: 6000 # 設定hystrix的逾時時間為6000ms
在配置熔斷的逾時時間時要大于Ribbon重試的逾時時間,即保證在熔斷前,重試能夠生效。