

得物App全栈可观测平台落地实践_架构_XYZ_InfoQ精选文章



import java.util.*;
import java.util.stream.Collectors;
// 灰度数据类型枚举
enum GrayDataType {
VERSION("version"),
STRING("string"),
SEGMENT("segment"),
NUMBER("number"),
NONE("none");
private final String type;
GrayDataType(String type) {
this.type = type;
}
public String getType() {
return type;
}
}
// 灰度规则枚举
enum PredicateType {
IS_IN("in"),
IS_NOT_IN("notIn"),
REGEX("regex"),
NREGEX("nregex"),
EQ("eq"),
NEQ("neq"),
EQUAL_TO("="),
NOT_EQUAL_TO("!="),
GREATER_THAN(">"),
GREATER_OR_EQUAL(">="),
LESS_THAN("<"),
LESS_OR_EQUAL("<="),
NONE("none");
private final String predicate;
PredicateType(String predicate) {
this.predicate = predicate;
}
public String getPredicate() {
return predicate;
}
}
// 灰度条件
class Condition {
private String type;
private String subject;
private String predicate;
private List<Object> objects;
// 省略构造函数、getter和setter
}
// 灰度规则
class Rule {
private List<Condition> conditions;
// 省略构造函数、getter和setter
}
// 灰度开关
class Toggle {
private Integer fullGray;
private Integer enabled;
private List<Rule> rules;
// 省略构造函数、getter和setter
// 判断是否命中灰度
public boolean hitGray(Map<String, Object> attrs) {
// 这里只是一个简化示例,实际逻辑会更复杂
return rules.stream().anyMatch(rule -> rule.conditions.stream().allMatch(condition -> {
Object attrValue = attrs.get(condition.getSubject());
switch (condition.getPredicate()) {
case "eq":
return Objects.equals(attrValue, condition.objects.get(0));
// 可以添加更多的case来处理不同的PredicateType
default:
return false;
}
}));
}
}
// 灰度服务接口
interface GrayService {
boolean hitGray(String sceneKey, Map<String, Object> attrs);
}
// 简易Demo
public class GrayDemo {
public static void main(String[] args) {
Map<String, Object> attrs = new HashMap<>();
attrs.put("userLevel", "VIP");
attrs.put("version", "1.2.3");
// 创建灰度开关示例
Toggle toggle = new Toggle();
toggle.setEnabled(1);
toggle.setFullGray(0);
List<Rule> rules = new ArrayList<>();
Rule rule = new Rule();
List<Condition> conditions = new ArrayList<>();
Condition condition = new Condition();
condition.setSubject("userLevel");
condition.setPredicate("eq");
condition.setObjects(Arrays.asList("VIP"));
rules.add(rule);
toggle.setRules(rules);
// 判断是否命中灰度
GrayService grayService = (sceneKey, attrsParam) -> toggle.hitGray(attrsParam);
boolean isHit = grayService.hitGray("sceneKey1", attrs);
System.out.println("Is hit gray: " + isHit);
}
}