【Spring Cloud 06】Hystrix
2021-02-27 15:56:10
引入pom依赖
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
```
启动类
```java
@EnableCircuitBreaker
@SpringBootApplication
@EnableFeignClients
public static void main(String[] args) {
SpringApplication.run(BarApplication.class, args);
}
```
服务类
```java
package com.example;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BarService {
@Autowired
FooClient fooClient;
@HystrixCommand(
fallbackMethod = "fallback",
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
},
threadPoolKey = "fooServiceThreadPool",
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "30"),
@HystrixProperty(name = "maxQueueSize", value = "10")
}
)
public String callFoo() {
return fooClient.version(); // 去 foo-service 中模拟随机超过2秒的高延时
}
private String fallback() {
return "降级内容";
}
}
```
控制器
```java
@RestController
class TestController{
@Autowired
BarService barService;
@GetMapping("/test")
public String test() {
return barService.callFoo();
}
}
```