Spring Cloud Hystrix 实例学习

Hystrix 是 Spring Cloud 框架从 Netflix 引入的服务熔断、降级组件。

线程池隔离

1. 不使用线程池隔离的例子

我们先看看不使用Hystrix线程池隔离怎么做(即普通做法)

在Consumer端,新建两个Service接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Service
public class ClientServiceImpl implements ClientService {

@Override
public String thread1() {
System.out.println(Thread.currentThread().getName());
return null;
}

@Override
public String thread2() {
System.out.println(Thread.currentThread().getName());
return null;
}
}

在Controller中进行调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
@RestController
public class ClientController {

@Autowired
public ClientService clientService;

@RequestMapping("/thread")
public String thread() {
clientService.thread1();
clientService.thread2();
return "OK";
}
}

调用/thread接口:

1
curl http://localhost:8080/thread

返回”OK”,同时可以在Consumer服务控制台看到打印输出:

http-nio-8080-exec-1
http-nio-8080-exec-1

这说明thread1和thread2两个接口使用的是同一个线程(http-nio-8080-exec-1)处理的。

2. 配置Hystrix线程池隔离

接上面的代码,在thread1函数上添加@HystrixCommand注解:

1
2
3
4
5
6
7
8
9
10
11
@HystrixCommand(groupKey = "wsd", commandKey = "abc", threadPoolKey = "wsd", threadPoolProperties = {
@HystrixProperty(name = HystrixPropertiesManager.CORE_SIZE, value = "4"),
@HystrixProperty(name = HystrixPropertiesManager.MAX_QUEUE_SIZE, value = "5"),
@HystrixProperty(name = HystrixPropertiesManager.KEEP_ALIVE_TIME_MINUTES, value = "2"),
@HystrixProperty(name = HystrixPropertiesManager.QUEUE_SIZE_REJECTION_THRESHOLD, value = "5")
})
@Override
public String thread1() {
System.out.println(Thread.currentThread().getName());
return null;
}

另外不要忘记Consumer的启动类上添加了 @EnableCircuitBreaker 注解。

再次运行curl测试接口

可以看到打印输出变为:

hystrix-wsd-1
http-nio-8080-exec-1

这说明thread1的处理线程发生了改变,变成了由Hystrix托管的线程池中的一个线程(hystrix-wsd-1)

Spring Cloud Gateway实验 Kubernetes云原生学习

评论

You forgot to set the shortname for Disqus. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×