Sentinel集成zookeeper注册中心
Sentinel 是什么
随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 是面向分布式服务架构的轻量级流量控制框架,主要以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度来帮助您保护服务的稳定性。
Sentinel 的历史
- 2012 年,Sentinel 诞生,主要功能为入口流量控制。
- 2013-2017 年,Sentinel 在阿里巴巴集团内部迅速发展,成为基础技术模块,覆盖了所有的核心场景。Sentinel 也因此积累了大量的流量归整场景以及生产实践。
- 2018 年,Sentinel 开源。
Sentinel 基本概念
资源
资源是 Sentinel 的关键概念。它可以是 Java 应用程序中的任何内容,例如,由应用程序提供的服务,或由应用程序调用的其它应用提供的服务,甚至可以是一段代码。在接下来的文档中,我们都会用资源来描述代码块。
只要通过 Sentinel API 定义的代码,就是资源,能够被 Sentinel 保护起来。大部分情况下,可以使用方法签名,URL,甚至服务名称作为资源名来标示资源。
规则
围绕资源的实时状态设定的规则,可以包括流量控制规则、熔断降级规则以及系统保护规则。所有规则可以动态实时调整。
Sentinel 功能和设计理念
流量控制
什么是流量控制
流量控制在网络传输中是一个常用的概念,它用于调整网络包的发送数据。然而,从系统稳定性角度考虑,在处理请求的速度上,也有非常多的讲究。任意时间到来的请求往往是随机不可控的,而系统的处理能力是有限的。我们需要根据系统的处理能力对流量进行控制。Sentinel 作为一个调配器,可以根据需要把随机的请求调整成合适的形状,如下图所示:
流量控制设计理念
流量控制有以下几个角度:
- 资源的调用关系,例如资源的调用链路,资源和资源之间的关系;
- 运行指标,例如 QPS、线程池、系统负载等;
- 控制的效果,例如直接限流、冷启动、排队等。
Sentinel 的设计理念是让您自由选择控制的角度,并进行灵活组合,从而达到想要的效果。
熔断降级
什么是熔断降级
除了流量控制以外,降低调用链路中的不稳定资源也是 Sentinel 的使命之一。由于调用关系的复杂性,如果调用链路中的某个资源出现了不稳定,最终会导致请求发生堆积。这个问题和 Hystrix 里面描述的问题是一样的。
Sentinel 和 Hystrix 的原则是一致的: 当调用链路中某个资源出现不稳定,例如,表现为 timeout,异常比例升高的时候,则对这个资源的调用进行限制,并让请求快速失败,避免影响到其它的资源,最终产生雪崩的效果。
熔断降级设计理念
在限制的手段上,Sentinel 和 Hystrix 采取了完全不一样的方法。
Hystrix 通过线程池的方式,来对依赖(在我们的概念中对应资源)进行了隔离。这样做的好处是资源和资源之间做到了最彻底的隔离。缺点是除了增加了线程切换的成本,还需要预先给各个资源做线程池大小的分配。
Sentinel 对这个问题采取了两种手段:
- 通过并发线程数进行限制
和资源池隔离的方法不同,Sentinel 通过限制资源并发线程的数量,来减少不稳定资源对其它资源的影响。这样不但没有线程切换的损耗,也不需要您预先分配线程池的大小。当某个资源出现不稳定的情况下,例如响应时间变长,对资源的直接影响就是会造成线程数的逐步堆积。当线程数在特定资源上堆积到一定的数量之后,对该资源的新请求就会被拒绝。堆积的线程完成任务后才开始继续接收请求。
- 通过响应时间对资源进行降级
除了对并发线程数进行控制以外,Sentinel 还可以通过响应时间来快速降级不稳定的资源。当依赖的资源出现响应时间过长后,所有对该资源的访问都会被直接拒绝,直到过了指定的时间窗口之后才重新恢复。
系统负载保护
Sentinel 同时对系统的维度提供保护。防止雪崩,是系统防护中重要的一环。当系统负载较高的时候,如果还持续让请求进入,可能会导致系统崩溃,无法响应。在集群环境下,网络负载均衡会把本应这台机器承载的流量转发到其它的机器上去。如果这个时候其它的机器也处在一个边缘状态的时候,这个增加的流量就会导致这台机器也崩溃,最后导致整个集群不可用。
针对这个情况,Sentinel 提供了对应的保护机制,让系统的入口流量和系统的负载达到一个平衡,保证系统在能力范围之内处理最多的请求。
Sentinel 是如何工作的
Sentinel 的主要工作机制如下:
- 对主流框架提供适配或者显示的 API,来定义需要保护的资源,并提供设施对资源进行实时统计和调用链路分析。
- 根据预设的规则,结合对资源的实时统计信息,对流量进行控制。同时,Sentinel 提供开放的接口,方便您定义及改变规则。
- Sentinel 提供实时的监控系统,方便您快速了解目前系统的状态。
以上介绍来自github下面简单介绍下怎样集成zookeeper注册中心实现规则动态发现,当然这里还可以集成nacos等其他数据源。
实现原理
从 Sentinel 1.4.0 开始,Sentinel 控制台提供 DynamicRulePublisher
和 DynamicRuleProvider
接口用于实现应用维度的规则推送和拉取。
主要扩展使用类:
com.taobao.csp.sentinel.dashboard.client.ZookeeperClient、
com.taobao.csp.sentinel.dashboard.config.ZookeeperConfig、
com.taobao.csp.sentinel.dashboard.rule.FlowRuleZKProvider、
com.taobao.csp.sentinel.dashboard.rule.FlowRuleZKPublisher
说明:
ZookeeperClient: zookeeper数据读取、写入、连接
public class ZookeeperClient {
private static final int RETRY_TIMES = 3;
private static final int SLEEP_TIME = 1000;
private String remoteAddress;
private String groupId;
private String dataId;
Logger logger = Logger.getLogger(ZookeeperClient.class);
public ZookeeperClient(String remoteAddress,String groupId,String dataId){
this.remoteAddress = remoteAddress;
this.groupId = groupId;
this.dataId = dataId;
}
public void write(String rule){
try {
CuratorFramework zkClient = CuratorFrameworkFactory.newClient(remoteAddress, new ExponentialBackoffRetry(SLEEP_TIME, RETRY_TIMES));
zkClient.start();
String path = getPath(groupId, dataId);
Stat stat = zkClient.checkExists().forPath(path);
if (stat == null) {
zkClient.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, null);
}
zkClient.setData().forPath(path, rule.getBytes());
zkClient.getData().forPath(path);
zkClient.close();
} catch (Exception e) {
logger.error("写配置中心zookeeper异常:",e);
}
}
public String read(){
try {
CuratorFramework zkClient = CuratorFrameworkFactory.newClient(remoteAddress, new ExponentialBackoffRetry(SLEEP_TIME, RETRY_TIMES));
zkClient.start();
String path = getPath(groupId, dataId);
Stat stat = zkClient.checkExists().forPath(path);
if (stat == null) {
zkClient.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, null);
}
byte[] bytes = zkClient.getData().forPath(path);
zkClient.close();
return new String(bytes,"UTF-8");
} catch (Exception e) {
logger.error("写配置中心zookeeper异常:",e);
}
return null;
}
private static String getPath(String groupId, String dataId) {
String path = "";
if (groupId.startsWith("/")) {
path += groupId;
} else {
path += "/" + groupId;
}
if (dataId.startsWith("/")) {
path += dataId;
} else {
path += "/" + dataId;
}
return path;
}
}
ZookeeperConfig:zookeeper数据转换器配置
@Configuration
public class ZookeeperConfig {
@Bean
public Converter<List<FlowRuleEntity>, String> flowRuleEntityEncoder() {
return JSON::toJSONString;
}
@Bean
public Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() {
return s -> JSON.parseArray(s, FlowRuleEntity.class);
}
}
FlowRuleZKProvider:zookeeper数据拉取
/**
* @author ouwen
* @since 1.4.0
*/
@Component("flowRuleZKProvider")
public class FlowRuleZKProvider implements DynamicRuleProvider<List<FlowRuleEntity>> {
@Autowired
private Converter<String, List<FlowRuleEntity>> converter;
@Override
public List<FlowRuleEntity> getRules(String appName) throws Exception {
//zookeeper地址
String zookeeper = System.getProperty("csp.sentinel.zookeeper");
//zookeeper访问path=/${groupId}/${dataId}
String groupId = System.getProperty("csp.sentinel.groupId");
String dataId = System.getProperty("csp.sentinel.dataId");
ZookeeperClient zookeeperClient = new ZookeeperClient(zookeeper,groupId,dataId);
String rules = zookeeperClient.read();
if (StringUtil.isEmpty(rules)) {
return new ArrayList<>();
}
return converter.convert(rules);
}
}
FlowRuleZKPublisher:zookeeper数据推送
/**
* @author ouwen
* @since 1.4.0
*/
@Component("flowRuleZKPublisher")
public class FlowRuleZKPublisher implements DynamicRulePublisher<List<FlowRuleEntity>> {
@Autowired
private Converter<List<FlowRuleEntity>, String> converter;
@Override
public void publish(String app, List<FlowRuleEntity> rules) throws Exception {
AssertUtil.notEmpty(app, "app name cannot be empty");
if (rules == null) {
return;
}
String zookeeper = System.getProperty("csp.sentinel.zookeeper");
String groupId = System.getProperty("csp.sentinel.groupId");
String dataId = System.getProperty("csp.sentinel.dataId");
ZookeeperClient zookeeperClient = new ZookeeperClient(zookeeper,groupId,dataId);
zookeeperClient.write(converter.convert(rules));
}
}
最后需要修改FlowControllerV2类中规则拉取/推送实现bean
@Autowired
// @Qualifier("flowRuleDefaultProvider")
@Qualifier("flowRuleZKProvider")
private DynamicRuleProvider<List<FlowRuleEntity>> ruleProvider;
@Autowired
// @Qualifier("flowRuleDefaultPublisher")
@Qualifier("flowRuleZKPublisher")
private DynamicRulePublisher<List<FlowRuleEntity>> rulePublisher;
最后使用maven命令重新打包即可,sentinel-dashboard即制作完成,启动
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -Dcsp.sentinel.zookeeper=192.168.5.4:2181 -Dcsp.sentinel.groupId=Sentinel -Dcsp.sentinel.dataId=alarm-flow-rules -jar sentinel-dashboard.jar
参数说明:
csp.sentinel.zookeeper 注册中心地址
csp.sentinel.groupId zk规则路径
csp.sentinel.dataId zk规则路径
最终在zookeeper上存放路径:/${csp.sentinel.groupId }/${csp.sentinel.dataId}
在客户端使用的时候需要绑定注册中心数据源:
//注册规则中心
ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<>(sentinelProperties.getZookeeper(), sentinelProperties.getRulePath(),
source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}));
FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
特别重要的地方默认的访问配置规则地址:以下访问方式是默认存放在内存中
http://127.0.0.1:8080/#/dashboard/flow/sentinel-dashboard
拓展zookeeper注册中心后访问地址: 以下访问方式走的拓展推送/拉取实例(FlowRuleZKProvider、FlowRuleZKPublisher)
http://127.0.0.1:8080/#/dashboard/v2/flow/sentinel-dashboard
sentinel-dashboard下载地址:
https://pan.baidu.com/s/1JIS6NzShfaWNv6szhXj8ag
sentinel开源地址:
https://github.com/alibaba/Sentinel.git