分布式系统的延时和故障容错之Spring Cloud Hystrix (3)

控制器ConsumerController.java

package com.easy.serviceConsumer.web; import com.easy.serviceConsumer.service.HelloService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class ConsumerController { @Autowired HelloService helloService; @GetMapping("hello") public String hello(@RequestParam String p1, @RequestParam String p2) { System.out.println("hello"); return helloService.hello(p1, p2); } } 4.启动类HystrixServiceConsumerApplication.java package com.easy.serviceConsumer; import org.springframework.boot.SpringApplication; import org.springframework.cloud.client.SpringCloudApplication; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringCloudApplication public class HystrixServiceConsumerApplication { @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(HystrixServiceConsumerApplication.class, args); } } 使用示例

分别运行3个服务,HystrixEurekaServerApplication.java(服务注册中心),HystrixServiceProviderApplication.java(服务提供者),HystrixServiceConsumerApplication.java(服务消费者)

1.访问 :8080/hello?p1=a&p2=b ,正常情况下响应为 hello, a, b

2.关闭 hystrix-service-provider 或在 sleepTime 超过 1000ms 时,访问 :8080/hello?p1=a&p2=b,执行降级逻辑,返回 error, a, b

资料

Spring Cloud Hystrix 示例源码

Spring Boot、Spring Cloud示例学习

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyysxz.html