在生产环境中使用 Sentinel
原创
©著作权归作者所有:来自51CTO博客作者gblfy的原创作品,请联系作者获取转载授权,否则将追究法律责任

文章目录
分布式限流 Sentinel+Zookkeper
https://github.com/alibaba/Sentinel/wiki/在生产环境中使用-Sentinel
一、安装zookeeper
1. linux环境


注:这个zookeeper版本建议使用3.5.8,curator4.x对应zookeeper版本3.5.x
2. windows环境
将zoo_sample.cfg重命名zoo.cfg:

双击启动zk

2. 安装并启动zkui
linux环境:
nohup java -jar zkui-2.0-SNAPSHOT-jar-with-dependencies.jar &
windows环境
java -jar zkui-2.0-SNAPSHOT-jar-with-dependencies.jar >>


二、编译打包
2.1. 拉取项目
git clone git@github.com:jiajiangnan/Sentinel.git
cd Sentinel
mvn clean install


2.2. 启动
#进入编译后的目录
cd Sentinel-master\Sentinel-master\sentinel-dashboard\target
# 第一种(推荐使用):sentinel启动本地连接zk 没任何问题
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -Ddatasource.provider=zookeeper -Ddatasource.provider.zookeeper.server-addr=localhost:2181 -jar sentinel-dashboard-1.8.0-zookeeper.jar
注:jar待补充

2.3. 登录 sentinel
账号/密码:sentinel/sentinel



2.4. 登录zkui

2.5. 重启Sentinel
查看流控规则是否仍然存在

2.6. 删除Sentinel的流控规则
因为流控规则是Sentinel控制台同步zk的,预期效果,在Sentinel控制台删除流控规则后,zk的流控规则也会删除



符合预期
三、将客户端和zk打通
https://github.com/alibaba/Sentinel/wiki/动态规则扩展
3.1. 引入依赖
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-zookeeper</artifactId>
</dependency>
3.2. 配置
package com.gblfy.distributedlimiter.config;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.zookeeper.ZookeeperDataSource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.List;
@Component//添加到spring把容器让spring管理
public class ZookeeperDataSourceConfig {
@Bean//启动加载此方法
public void loadRules() {
//zk服务端地址
final String remoteAddress = "192.168.43.119:2181";
//应用+keyName
final String path = "/limiter/sentinel-flow-rules";
ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<>(remoteAddress, path,
source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
}));
FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
}
}
3.3. 启动springboot

3.4. sentinel控制台+添加流控规则


3.5. 登录zkui
查看流控规则是否同步

四、测试
4.1. 请求
请求数量>1,预期会被限流
http://192.xxx.x.xxx:8082/sentinel

4.2. 重启springboot项目
lue
4.3. Sentinel控制台
查看流控规则是否仍然存在

4.4. zkui

4.5. 分布式限流总结
对于是否是分布式限流,明确的就是限流规则是否储存在外部的一个公用的存储中心。之前讲的Guava RateLimiter组件限流为什么不能做不到分布式呢?因为限流规则存在java应用内存里面的。