上篇文章我们配置了Eureka集群,实现了高可用。在微服务框架中,一个服务消费者可能是其他服务消费者的提供者,而当低层次的服务提供者出现问题时,会导致系统资源被耗尽。出现雪崩效应。
Hystrix是解决解决方案的实践。
消费者服务:microservice-comsumer-movie-ribbon-withhystrix
1.POM.xml中加入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
2.在启动来上加入注解:
@EnableCircuitBreaker
3.Controller中加入注解和失败调用方式
package com.dynamic.cloud.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.dynamic.cloud.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
@RestController
public class MovieController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/movie/{id}")
@HystrixCommand(fallbackMethod = "findByIdFallback")
public User findById(@PathVariable Long id) {
return this.restTemplate.getForObject("http://microservice-provider-user/simple/" + id, User.class);
}
public User findByIdFallback(Long id) {
User user = new User();
user.setId(0L);
return user;
}
}
4.配置文件 application.yml
server:
port: 7901
spring:
application:
name: microservice-comsumer-movie-ribbon
eureka:
client:
serviceUrl:
defaultZone: http://user:pass123@localhost:8761/eureka
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
#hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
启动Eureka,用户微服务,电影微服务。
直接访问,出现数据访问成功,而当我们把用户微服务停掉的时候,再次访问就会走我们的fallbackMethod配置的方法。