控制器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示例学习