一、熔断简单案例
在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重试的超时时间,即保证在熔断前,重试能够生效。