SpringCloud--Hystrix--使用demo
在之前的文章中,我們寫的呼叫方法是直接呼叫hello服務請求,程式碼如下:
@Autowired RestTemplate restTemplate; @GetMapping("/helloConsumer") public String getStr() { return restTemplate.getForEntity("http://EUREKA-CLIENT/v1/hello", String.class).getBody(); }
然後我們可以模擬異常狀況,例如呼叫超時或服務不存在,我們在這裡模擬一下服務超時。
調整提供服務的hello方法,設定介面一個隨機的睡眠時間,以模擬請求超時場景(Hystirx預設超時時間是2秒,這裡採用0-4000的隨機數來模擬休眠時間,大大提高了超時的機率)
@RestController
@RequestMapping("/v1")
@Slf4j
public class HelloApi {
@GetMapping("/hello")
public String hello() throws InterruptedException {
long start = System.currentTimeMillis();
log.info("===========");
int sleepTime = new Random().nextInt(4000);
Thread.sleep(sleepTime);
log.info("return hello;time:【{}】", System.currentTimeMillis() - start);
return "hello......";
}
}
當我們請求超時時,我們拿到的返回結果是500
{ "timestamp": "2020-10-23T12:19:31.830+00:00", "status": 500, "error": "Internal Server Error", "message": "", "path": "/v1/helloConsumer" }
接下來,我們可以使用Hystrix來對專案做一個改造
第一步:引入包Hystrix包
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
第二步:在啟動類上新增@EnableCircuitBreaker註解
//開啟服務發現 @EnableDiscoveryClient @SpringBootApplication //開啟斷路器 @EnableCircuitBreaker //以上所有配置可以統一使用@SpringCloudApplication替換 public class SpringCloudDemoApplication { @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(SpringCloudDemoApplication.class, args); } }
可以看到程式碼裡面有三個註解,分別為@EnableDiscoveryClient、@SpringBootApplication、@EnableCircuitBreaker,這裡可以使用@SpringCloudApplication來直接替代這三個註解,檢視該註解的原始碼可以發現,@SpringCloudApplication註解裡面就是使用了@EnableDiscoveryClient、@SpringBootApplication、@EnableCircuitBreaker這三個註解,也就是說,一個SpringCloud專案,預設要有服務發現和熔斷功能。
第三步:對入口專案做專案改造,Controller呼叫Service,在Service中做熔斷處理
@Autowired private HelloService helloService; @GetMapping("/helloConsumer1") public String getStr1(String d) { return helloService.getStr(); }
第四步:然後在Service中設定回撥方法
@Slf4j @Service public class HelloService { @Autowired RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "fallBack") public String getStr() { long start = System.currentTimeMillis(); String str = restTemplate.getForEntity("http://EUREKA-CLIENT/v1/hello", String.class).getBody(); log.info("time:【{}】", System.currentTimeMillis() - start); return str; } public String fallBack() { return "error"; } }
可以看到Service中,寫了一個fallBack方法,然後在getStr方法上加了@HystrixCommand註解,並設定異常回調方法fallBack。
然後訪問http://localhost:5551/v1/helloConsumer1,如果超時,我們拿到的返回結果就是error,到此,整個Hystrix的使用方法已經說完,總體來說非常簡單,但是具體他的實現原理是什麼呢,下一章繼續。