@EnableDiscoveryClient @SpringBootApplication @EnableCircuitBreaker //开启断路器 public class ConsumerMovieApplication { @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(ConsumerMovieApplication.class, args); } }
调用了findByIdFallback,并不代表使用了断路器,可以通过 /health 查看是否启用了断路器
@RestController public class MovieController { private static final Logger LOGGER = LoggerFactory.getLogger(MovieController.class); @Autowired private RestTemplate restTemplate; @Autowired private LoadBalancerClient loadBalancerClient; //断路器 配置 fallbackMethod ,返回值和参数与调用一致 @HystrixCommand(fallbackMethod = "findByIdFallback") @GetMapping("/user/{id}") public User findById(@PathVariable Long id) { // 当microservice-provider-user 挂掉了,就返回 findByIdFallback,而不在调用服务了 return this.restTemplate.getForObject("http://microservice-provider-user/" + id, User.class); } public User findByIdFallback(Long id) { User user = new User(); user.setId(-1L); user.setName("默认用户"); return user; } @GetMapping("/log-user-instance") public void logUserInstance() { ServiceInstance serviceInstance = this.loadBalancerClient.choose("microservice-provider-user"); // 打印当前选择的是哪个节点 MovieController.LOGGER.info("{}:{}:{}", serviceInstance.getServiceId(), serviceInstance.getHost(), serviceInstance.getPort()); } }
1.如何实现自定义路由算法
1.实现 IRule 接口
2.实例化 接口
2.为服务名称users 配置 IRule
users.ribbon.NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule
3.设置调用服务的超时配置
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000
s