2、开启服务降级org.springframework.cloud spring-cloud-starter-netflix-hystrix
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class ConsumerApp {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args){
SpringApplication.run(ConsumerApp.class,args);
}
}
3、重新写方法
因为默认使用了Hystrix,所以要处理一下方法,如果失败之后返回信息
@GetMapping("/student/{ids}")
@HystrixCommand(fallbackMethod = "studentsFallBack")
public List student(@PathVariable("ids") List ids){
List list = new ArrayList<>();
ids.forEach(id->{
//远程调用,更改路径(需要开启负载均衡)
String url = "http://user-service/student/"+id;
Student student = restTemplate.getForObject(url, Student.class);
list.add(student);
});
return list;
}
public List studentsFallBack(@PathVariable("ids") List ids){
List list = new ArrayList<>();
for(Integer id : ids){
Student student = new Student();
student.setName("请求超时!");
list.add(student);
}
return list;
}
4、改造user-service
为了能够模拟超时,需要改造一下user-service,让其返回结果慢一点返回
@GetMapping("/student/{id}")
public Student student(@PathVariable("id") int id){
try {
Thread.sleep(2000L);
}catch (InterruptedException e){
e.printStackTrace();
}
return studentService.getById(id);
}
5、同步更新配置文件
性能都改为单台服务进行测试
eureka-server:
server:
port: 10086
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka/
spring:
application:
name: eureka-server
user-service:
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka/
instance:
instance-id: ${spring.application.name}:${server.port}
consumer-demo:
server:
port: 9000
spring:
application:
name: consumer-demo
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka/
user-service:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule



