1.启动server中心项目
java -jar E:\ideaWork\cloudLearn\eureka-client\target\eureka-server-0.0.1-SNAPSHOT.jar
2.启动两个不同端口的hello-service项目
java -jar E:\ideaWork\cloudLearn\eureka-client\target\eureka-client-0.0.1-SNAPSHOT.jar --server.port=8081
java -jar E:\ideaWork\cloudLearn\eureka-client\target\eureka-client-0.0.1-SNAPSHOT.jar --server.port=8082
3.启动ribbon-consumer项目
4.请求ribbon-consumer项目接口调用hello-service的服务:http://localhost:8763/ribbon-consumer,按照负载均衡策略,两个控制台轮流打印相关日志
5.关闭8081端口的service服务,然后继续请求ribbon-consumer项目接口调用hello-service的服务:http://localhost:8763/ribbon-consumer,会受到错误返回如下:
6.我们在ribbon-consumer项目里面引入spring cloud hystrix
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency>
7.在ribbon-consumer项目的application主类上面加上@EnableCircuitBreaker注解开启断路器功能
8.新建service来调用hello-service服务
@Service public class HelloService { @Autowired RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "helloFallBack") public String helloService(){ return restTemplate.getForEntity("http://hello-service/hello",String.class).getBody(); } public String helloFallBack(){ return "error"; } }
9.新建接口调用helloservice
@RestController public class HelloServiceController { @Autowired private HelloService helloService; @RequestMapping("/showHelloService") public String showHelloService(){ return helloService.helloService(); } }
10.打开hello-service8081端口的服务,调用刚写的HelloServiceController :http://localhost:8763/showHelloService,两个服务端控制台轮流打印日志,停掉8081端口的服务时,返回如下:
说明helloservice中的回调已经生效了
11.我们修改hello-service服务,使用Thread.sleep()方法模拟服务阻塞。由于Hystrix默认的超时时间为2000ms,我们采用0-3000的随机数
int sleepTime = new Random().nextInt(3000); logger.info("sleep time = "+sleepTime); Thread.sleep(sleepTime);
12.重新启动8081和8082端口的service服务,然后调用:http://localhost:8763/showHelloService,发现在阻塞超过2000ms的时候会返回error,说明断路器生效,示例完成。