SpringCloud自学入门-服务容错保护Hystrix

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,说明断路器生效,示例完成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值