1.服务消费者pom.xml引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2.启动类开启Hystrix
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker //开启熔断
//@SpringCloudApplication = 上面三个注解
public class AutoApplication {
public static void main(String[] args) {
SpringApplication.run(AutoApplication.class,args);
}
@LoadBalanced
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
3.请求调用的方法上加上@HystrixCommand注解
@HystrixCommand(
commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="2000")
},
fallbackMethod = "MyFallBack" //回退方法
)
@GetMapping("checkStateTimeOut/{userId}")
public Integer findByResumeTimeOut(@PathVariable Long userId){
String url = "http://find/resume/openstate/"+userId;
System.out.println(url);
return restTemplate.getForObject(url,Integer.class);
}
//回退
public Integer MyFallBack(Long userId){
return -1;//兜底数据
}
4.Hystrix的舱壁模式
默认所有熔断方法公用一个线程池,线程池的大小为10
可以给每个熔断方法设置单独的线程池
@HystrixCommand(
threadPoolKey = "findByResumeTimeOut",
threadPoolProperties = {
@HystrixProperty(name="coreSize",value = "5"),
@HystrixProperty(name="maxQueueSize",value="20")
},
commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="2000")
},
fallbackMethod = "MyFallBack"
)
@GetMapping("checkStateTimeOut/{userId}")
public Integer findByResumeTimeOut(@PathVariable Long userId){
String url = "http://find/resume/openstate/"+userId;
System.out.println(url);
return restTemplate.getForObject(url,Integer.class);
}
可以用jps命令查看所有java进程
然后用jstack 进程号查看当前进程的线程信息