1.配置依赖
org.springframework.cloud
spring-cloud-starter-hystrix
2.入口程序上增加@EnableCircuitBreaker注解
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableCircuitBreaker
@ComponentScan(excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, value = ExcludeFromComponentScan.class) })
public class MicroserviceConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(MicroserviceConsumerApplication.class, args);
}
}
3.配置文件配置hystrix默认超时时间,默认即为5000,如无特殊需求不要更改
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
1.首先开启对全局Hystrix的支持,旧版中默认是开启,现在的版本则是默认false
2.为feignClient添加fallback
@FeignClient(name = "microservice-provider", fallback = HystrixClientFallback.class)
public interface UserFeignClient {
@RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)
public User findById(@PathVariable("id") Long id);
}
3.fallback 类要继承feignClient接口,并实现方法。如果feign访问其它微服务失败,则调用fallback 对应的方法返回默认值。
public class HystrixClientFallback implements UserFeignClient {
@Override
public User findById(Long id) {
User user = new User();
user.setId(0L);
return user;
}
}
@SuppressWarnings("SpringJavaAutowiringInspection")
@Autowired
private UserFeignClient userFeignClient;
@HystrixCommand(fallbackMethod = "findByIdFallback",commandProperties = @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE"))
@GetMapping("/movief/{id}")
public User findByFeginId(@PathVariable Long id) {
return userFeignClient.findById(id);
}
public User findByIdFallback(Long id) {
User user = new User();
user.setId(6L);
return user;
}
1.feignClient
@FeignClient(name = "microservice-provider", fallbackFactory = HystrixClientFactory.class)
public interface UserFeignClient {
@RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)
public User findById(@PathVariable("id") Long id); // 两个坑:1. @GetMapping不支持 2. @PathVariable得设置value
@RequestMapping(value = "/user", method = RequestMethod.POST)
public User postUser(@RequestBody User user);
}
2.fallbackFactory实现
@Component
public class HystrixClientFactory implements FallbackFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(HystrixClientFactory.class);
@Override
public UserFeignClient create(Throwable throwable) {
HystrixClientFactory.LOGGER.info("fallback; reason was: {}", throwable.getMessage());
return new HystrixClientFallback();
}
}
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
return Feign.builder();
}
http://localhost:8032/hystrix.stream 查看Hystrix信息 http://localhost:8032/health 查看监控状态
1.新建一个springboot项目
2.添加依赖
org.springframework.cloud
spring-cloud-starter-hystrix-dashboard
3.入口程序上增加@EnableHystrixDashboard注解
@EnableHystrixDashboard
@SpringBootApplication
public class HystrixDashBoardApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixDashBoardApplication.class, args);
}
}
4.配置端口
server.port= 8060