规则管理及推送
一般来说,规则的推送有下面三种模式:
推送模式 | 说明 | 优点 | 缺点 |
---|---|---|---|
原始模式 | API 将规则推送至客户端并直接更新到内存中,扩展写数据源(WritableDataSource ) |
简单,无任何依赖 | 不保证一致性;规则保存在内存中,重启即消失。严重不建议用于生产环境 |
Pull 模式 | 扩展写数据源(WritableDataSource ), 客户端主动向某个规则管理中心定期轮询拉取规则,这个规则中心可以是 RDBMS、文件 等 |
简单,无任何依赖;规则持久化 | 不保证一致性;实时性不保证,拉取过于频繁也可能会有性能问题。 |
Push 模式 | 扩展读数据源(ReadableDataSource ),规则中心统一推送,客户端通过注册监听器的方式时刻监听变化,比如使用 Nacos、Zookeeper 等配置中心。这种方式有更好的实时性和一致性保证。生产环境下一般采用 push 模式的数据源。
|
规则持久化;一致性;快速 | 引入第三方依赖 |
原始模式
pull模式
push模式
dashboard改造
1、下载源码
https://github.com/alibaba/Sentinel
主要改造dashboard这个module,我们将改造后的controller放在v2包下
2、分析改造方式
-
下图为限流controller的V1接口采用的上面讲的pull模式
-
在v2包中官方提供了限流接口push模式的demo,规则中心使用的nacos
3、改造方向
- 改造降级规则
- 规则中心使用zookeeper
- 使用push模式
3.1 pom依赖
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>${curator.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-zookeeper</artifactId>
<version>1.6.3</version>
</dependency>
3.2 zookeeper交互部分改造
3.2.1 获取规则
在rule包下有个DynamicRuleProvider接口。
public interface DynamicRuleProvider<T> {
T getRules(String appName) throws Exception;
}
通过实现这个接口给controller提供从zk中查询规则的方法。
ZookeeperConfigUtil
/**
* 获取appName对应的zk路径
* @author sunqiuxiang
*/
public class ZookeeperConfigUtil {
public static final String RULE_ROOT_PATH = "/Sentinel-Demo";
public static final int RETRY_TIMES = 3;
public static final int SLEEP_TIME = 1000;
public static String getPath(String appName) {
StringBuilder stringBuilder = new StringBuilder(RULE_ROOT_PATH);
if (StringUtils.isBlank(appName)) {
return stringBuilder.toString();
}
if (appName.startsWith("/")) {
stringBuilder.append(appName);
} else {
stringBuilder.append("/")
.append(appName);
}
return stringBuilder.toString();
}
}
DegradeZookeeperConfig
@Configuration
public class DegradeZookeeperConfig {
@Bean
public Converter<List<DegradeRuleEntity>, String> degradeRuleEntityEncoder() {
return JSON::toJSONString;
}
@Bean
public Converter<String, List<DegradeRuleEntity>> degradeRuleEntityDecoder() {
return s -> JSON.parseArray(s, DegradeRuleEntity.class);
}
@Bean
public CuratorFramework zkClient() {
CuratorFramework zkClient =
CuratorFrameworkFactory.newClient("127.0.0.1:2181",
new ExponentialBackoffRetry(ZookeeperConfigUtil.SLEEP_TIME, ZookeeperConfigUtil.RETRY_TIMES));
zkClient.start();
return zkClient;
}
}
DegradeRuleZookeeperProvider
@Component("degradeRuleZookeeperProvider")
public class DegradeRuleZookeeperProvider implements DynamicRuleProvider<List<DegradeRuleEntity>> {
@Autowired
private CuratorFramework zkClient;
@Autowired
private Converter<String, List<DegradeRuleEntity>> converter;
@Override
public List<DegradeRuleEntity> getRules(String appName) throws Exception {
String zkPath = ZookeeperConfigUtil.getPath(appName);
Stat stat;
// 判断路径是否存在
stat = zkClient.checkExists().forPath(zkPath);
if (stat == null) {
zkClient.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(zkPath, null);
}
// 获取path下的数据
byte[] bytes = zkClient.getData().forPath(zkPath);
if (null == bytes || bytes.length == 0) {
return new ArrayList<>();
}
String s = new String(bytes);
// 转成规则实体
return converter.convert(s);
}
}
3.2.2 发布规则
在rule包下有个DynamicRulePublisher接口。
public interface DynamicRulePublisher<T> {
/**
* Publish rules to remote rule configuration center for given application name.
*
* @param app app name
* @param rules list of rules to push
* @throws Exception if some error occurs
*/
void publish(String app, T rules) throws Exception;
}
通过实现这个接口给controller提供向zk发布规则的方法。
DegradeRuleZookeeperPublisher
@Component("degradeRuleZookeeperPublisher")
public class DegradeRuleZookeeperPublisher implements DynamicRulePublisher<List<DegradeRuleEntity>> {
@Autowired
private CuratorFramework zkClient;
@Autowired
private Converter<List<DegradeRuleEntity>, String> converter;
@Override
public void publish(String app, List<DegradeRuleEntity> rules) throws Exception {
AssertUtil.notEmpty(app, "app name cannot be empty");
String path = ZookeeperConfigUtil.getPath(app);
Stat stat;
try {
// 判断路径是否存在
stat = zkClient.checkExists().forPath(path);
if (stat == null) {
zkClient.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, null);
}
// 规则转成byte数组
byte[] data = CollectionUtils.isEmpty(rules) ? "[]".getBytes() : degradeRuleEntityEncoder().convert(rules).getBytes();
// set数据到app对应的路径下
zkClient.setData().forPath(path, data);
} catch (Exception e) {
e.printStackTrace();
}
}
private Converter<List<DegradeRuleEntity>, String> degradeRuleEntityEncoder() {
return JSON::toJSONString;
}
}
3.3 Controller改造
case,其他接口同理
@RestController
@RequestMapping(value = "/v2/degrade")
public class DegradeControllerV2 {
private final Logger logger = LoggerFactory.getLogger(DegradeControllerV2.class);
@Autowired
private InMemoryRuleRepositoryAdapter<DegradeRuleEntity> repository;
@Autowired
@Qualifier("degradeRuleZookeeperProvider")
private DynamicRuleProvider<List<DegradeRuleEntity>> ruleProvider;
@Autowired
@Qualifier("degradeRuleZookeeperPublisher")
private DynamicRulePublisher<List<DegradeRuleEntity>> rulePublisher;
@Autowired
private AuthService<HttpServletRequest> authService;
@GetMapping("/rules")
public Result<List<DegradeRuleEntity>> apiQueryMachineRules(HttpServletRequest request, @RequestParam String app) {
AuthUser authUser = authService.getAuthUser(request);
authUser.authTarget(app, PrivilegeType.READ_RULE);
if (StringUtil.isEmpty(app)) {
return Result.ofFail(-1, "app can't be null or empty");
}
try {
// 使用自己实现的provider获取规则
List<DegradeRuleEntity> rules = ruleProvider.getRules(app);
// 保存到内存中
rules = repository.saveAll(rules);
return Result.ofSuccess(rules);
} catch (Throwable throwable) {
logger.error("Error when querying flow rules", throwable);
return Result.ofThrowable(-1, throwable);
}
}
}
3.4 修改app.js
路径:resources/app/scripts/app.js
url改成自己定义的url