sentinel源码学习记录

109 阅读1分钟

在学习源码的过程中,遇到各式各样的问题,我选择记录下来,方便自己回顾

  1. 启动dashboard控制台的时候报错
    java: 程序包sun.net.util不存在

solution:

image.png

  1. 代码值得学习的地方

CAS设计标记变量

private static AtomicBoolean initialized = new AtomicBoolean(false);
if (!initialized.compareAndSet(false, true)) {
    return;
}

BIO的网络模型

    ServerSocket serverSocket = getServerSocketFromBasePort(port);

按照优先级别加载对应的配置文件

public static void load() {
    //从高到低加载配置
    // Order: system property -> system env -> default file (classpath:sentinel.properties) -> legacy path

    String fileName = System.getProperty(SENTINEL_CONFIG_PROPERTY_KEY);
    if (StringUtil.isBlank(fileName)) {
        fileName = System.getenv(SENTINEL_CONFIG_ENV_KEY);
        if (StringUtil.isBlank(fileName)) {
            fileName = DEFAULT_SENTINEL_CONFIG_FILE;
        }
    }

    Properties p = MyConfigUtil.loadProperties(fileName);
    if (p != null && !p.isEmpty()) {
        RecordLog.info("[SentinelConfigLoader] Loading Sentinel config from {}", fileName);
        properties.putAll(p);
    }

    for (Map.Entry<Object, Object> entry : new CopyOnWriteArraySet<>(System.getProperties().entrySet())) {
        String configKey = entry.getKey().toString();
        String newConfigValue = entry.getValue().toString();
        String oldConfigValue = properties.getProperty(configKey);
        properties.put(configKey, newConfigValue);
        if (oldConfigValue != null) {
            RecordLog.info("[SentinelConfigLoader] JVM parameter overrides {}: {} -> {}",
                    configKey, oldConfigValue, newConfigValue);
        }
    }
}

防御式编程

if (StringUtil.isBlank(app) || app.length() > 256) {
    return Result.ofFail(-1, "invalid appName");
}
if (StringUtil.isBlank(ip) || ip.length() > 128) {
    return Result.ofFail(-1, "invalid ip: " + ip);
}
if (!IPAddressUtil.isIPv4LiteralAddress(ip) && !IPAddressUtil.isIPv6LiteralAddress(ip)) {
    return Result.ofFail(-1, "invalid ip: " + ip);
}
if (port == null || port < -1) {
    return Result.ofFail(-1, "invalid port");
}
if (hostname != null && hostname.length() > 256) {
    return Result.ofFail(-1, "hostname too long");
}
if (port == -1) {
    logger.warn("Receive heartbeat from " + ip + " but port not set yet");
    return Result.ofFail(-1, "your port not set yet");
}