1、创建一个maven项目 hystrix-ribbon-threadpool-consumer
pom.xml
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
application.yml
spring:
application:
name: hystrix-ribbon-threadpool-consumer
server:
port: 8082
eureka:
client:
serviceUrl:
defaultZone: http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/
instance:
prefer-ip-address: true #默认是hostname注册,改成IP注册
2、Service服务线程隔离配置
@Service
public class StudentService {
@Autowired
private LoadBalancerClient loadBalancerClient;
/**
* 配置当并发高的时候服务降级,并返回拖底数据,防止服务雪崩
* @return
*/
@HystrixCommand(fallbackMethod="fallback", groupKey="eureka-provider", commandKey="studentList", threadPoolKey="eureka-provider",
threadPoolProperties = {
//线程池大小
@HystrixProperty(name = "coreSize", value = "30"),
//最大队列长度
@HystrixProperty(name = "maxQueueSize", value = "100"),
//线程存活时间
@HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),
//拒绝请求
@HystrixProperty(name = "queueSizeRejectionThreshold", value = "15")
})
public List<Student> studentList() {
// 获取服务端
ServiceInstance si = loadBalancerClient.choose("eureka-provider");//EUREKA-PROVIDER
// 拼装服务端地址
StringBuffer pUrl = new StringBuffer();
pUrl.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/list");
ParameterizedTypeReference<List<Student>> typeRef = new ParameterizedTypeReference<List<Student>>() {};
//远程调用获取提供者的数据
RestTemplate rt = new RestTemplate();
ResponseEntity<List<Student>> resp = rt.exchange(pUrl.toString(), HttpMethod.GET, null, typeRef);
List<Student> studentList = resp.getBody();
return studentList;
}
/**
* fallback返回拖底数据
* 以下四种情况将触发getFallback调用
* 1、方法抛出非HystrixBadRequestException异常。
* 2、方法调用超时
* 3、熔断器开启拦截调用
* 4、线程池/队列/信号量是否跑满
* @return
*/
public List<Student> fallback(){
List<Student> list = new ArrayList<Student>();
list.add(new Student("fallback",-1));
return list;
}
}
3、测试类
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("list")
public List<Student> list(){
return studentService.studentList();
}
}