Nacos配置中心——ConfigController

王守钰 2021-11-04 10:11:03

ConfigController

image
从图片中可以看到ConfigController包含了很多方法。从nacos的控制台进入查看配置列表信息请求接口。

ConfigController.searchConfig

@GetMapping(params = "search=accurate")
@Secured(action = ActionTypes.READ, parser = ConfigResourceParser.class)
public Page<ConfigInfo> searchConfig(@RequestParam("dataId") String dataId, @RequestParam("group") String group,
        @RequestParam(value = "appName", required = false) String appName,
        @RequestParam(value = "tenant", required = false, defaultValue = StringUtils.EMPTY) String tenant,
        @RequestParam(value = "config_tags", required = false) String configTags,
        @RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize) {
    Map<String, Object> configAdvanceInfo = new HashMap<String, Object>(100);
    if (StringUtils.isNotBlank(appName)) {
        configAdvanceInfo.put("appName", appName);
    }
    if (StringUtils.isNotBlank(configTags)) {
        configAdvanceInfo.put("config_tags", configTags);
    }
    try {
        return persistService.findConfigInfo4Page(pageNo, pageSize, dataId, group, tenant, configAdvanceInfo);
    } catch (Exception e) {
        String errorMsg = "serialize page error, dataId=" + dataId + ", group=" + group;
        LOGGER.error(errorMsg, e);
        throw new RuntimeException(errorMsg, e);
    }
}

public Page<ConfigInfo> findConfigInfo4Page(final int pageNo, final int pageSize, final String dataId,
        final String group, final String tenant, final Map<String, Object> configAdvanceInfo) {
    String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
    PaginationHelper<ConfigInfo> helper = createPaginationHelper();
    final String appName = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("appName");
    final String configTags = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("config_tags");
    String sqlCount = "SELECT count(*) FROM config_info";
    String sql = "SELECT id,data_id,group_id,tenant_id,app_name,content,type FROM config_info";
    StringBuilder where = new StringBuilder(" WHERE ");
    List<String> paramList = new ArrayList<String>();
    paramList.add(tenantTmp);
    if (StringUtils.isNotBlank(configTags)) {
        sqlCount = "SELECT count(*) FROM config_info  a LEFT JOIN config_tags_relation b ON a.id=b.id";
        sql = "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info  a LEFT JOIN "
                + "config_tags_relation b ON a.id=b.id";
        
        where.append(" a.tenant_id=? ");
        
        if (StringUtils.isNotBlank(dataId)) {
            where.append(" AND a.data_id=? ");
            paramList.add(dataId);
        }
        if (StringUtils.isNotBlank(group)) {
            where.append(" AND a.group_id=? ");
            paramList.add(group);
        }
        if (StringUtils.isNotBlank(appName)) {
            where.append(" AND a.app_name=? ");
            paramList.add(appName);
        }
        
        where.append(" AND b.tag_name IN (");
        String[] tagArr = configTags.split(",");
        for (int i = 0; i < tagArr.length; i++) {
            if (i != 0) {
                where.append(", ");
            }
            where.append('?');
            paramList.add(tagArr[i]);
        }
        where.append(") ");
    } else {
        where.append(" tenant_id=? ");
        if (StringUtils.isNotBlank(dataId)) {
            where.append(" AND data_id=? ");
            paramList.add(dataId);
        }
        if (StringUtils.isNotBlank(group)) {
            where.append(" AND group_id=? ");
            paramList.add(group);
        }
        if (StringUtils.isNotBlank(appName)) {
            where.append(" AND app_name=? ");
            paramList.add(appName);
        }
    }
    try {
        return helper.fetchPage(sqlCount + where, sql + where, paramList.toArray(), pageNo, pageSize,
                CONFIG_INFO_ROW_MAPPER);
    } catch (CannotGetJdbcConnectionException e) {
        LogUtil.FATAL_LOG.error("[db-error] " + e.toString(), e);
        throw e;
    }
}

查询配置列表分页,当没有传tag的时候,则执行SELECT id,data_id,group_id,tenant_id,app_name,content,type FROM config_info WHERE tenant_id=? AND data_id=? AND group_id=? AND app_name=?如果有tag的时候则会执行SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id WHERE a.tenant_id=? AND a.data_id=? AND a.group_id=? AND a.app_name=? AND b.tag_name IN (?)

ConfigController.detailConfigInfo

@GetMapping(params = "show=all")
@Secured(action = ActionTypes.READ, parser = ConfigResourceParser.class)
public ConfigAllInfo detailConfigInfo(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("dataId") String dataId, @RequestParam("group") String group,
        @RequestParam(value = "tenant", required = false, defaultValue = StringUtils.EMPTY) String tenant)
        throws NacosException {
    // check tenant
    ParamUtils.checkTenant(tenant);
    // check params
    ParamUtils.checkParam(dataId, group, "datumId", "content");
    return persistService.findConfigAllInfo(dataId, group, tenant);
}
public ConfigAllInfo findConfigAllInfo(final String dataId, final String group, final String tenant) {
    final String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
    try {
        List<String> configTagList = this.selectTagByConfig(dataId, group, tenant);
        ConfigAllInfo configAdvance = this.jt.queryForObject(
                "SELECT id,data_id,group_id,tenant_id,app_name,content,md5,"
                        + "gmt_create,gmt_modified,src_user,src_ip,c_desc,c_use,effect,type,c_schema FROM config_info "
                        + "WHERE data_id=? AND group_id=? AND tenant_id=?", new Object[] {dataId, group, tenantTmp},
                CONFIG_ALL_INFO_ROW_MAPPER);
        if (configTagList != null && !configTagList.isEmpty()) {
            StringBuilder configTagsTmp = new StringBuilder();
            for (String configTag : configTagList) {
                if (configTagsTmp.length() == 0) {
                    configTagsTmp.append(configTag);
                } else {
                    configTagsTmp.append(',').append(configTag);
                }
            }
            configAdvance.setConfigTags(configTagsTmp.toString());
        }
        return configAdvance;
    } catch (EmptyResultDataAccessException e) { // Indicates that the data does not exist, returns null
        return null;
    } catch (CannotGetJdbcConnectionException e) {
        LogUtil.FATAL_LOG.error("[db-error] " + e.toString(), e);
        throw e;
    }
}

查询配置信息的时候,会根据dataId,grouptenant来进行查询。执行sql为SELECT id,data_id,group_id,tenant_id,app_name,content,md5,gmt_create,gmt_modified,src_user,src_ip,c_desc,c_use,effect,type,c_schema FROM config_info WHERE data_id=? AND group_id=? AND tenant_id=?

ConfigController.publishConfig

@PostMapping
@Secured(action = ActionTypes.WRITE, parser = ConfigResourceParser.class)
public Boolean publishConfig(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "dataId") String dataId, @RequestParam(value = "group") String group,
        @RequestParam(value = "tenant", required = false, defaultValue = StringUtils.EMPTY) String tenant,
        @RequestParam(value = "content") String content, @RequestParam(value = "tag", required = false) String tag,
        @RequestParam(value = "appName", required = false) String appName,
        @RequestParam(value = "src_user", required = false) String srcUser,
        @RequestParam(value = "config_tags", required = false) String configTags,
        @RequestParam(value = "desc", required = false) String desc,
        @RequestParam(value = "use", required = false) String use,
        @RequestParam(value = "effect", required = false) String effect,
        @RequestParam(value = "type", required = false) String type,
        @RequestParam(value = "schema", required = false) String schema) throws NacosException {
    
    final String srcIp = RequestUtil.getRemoteIp(request);
    final String requestIpApp = RequestUtil.getAppName(request);
    srcUser = RequestUtil.getSrcUserName(request);
    //check type
    if (!ConfigType.isValidType(type)) {
        type = ConfigType.getDefaultType().getType();
    }
    // check tenant
    ParamUtils.checkTenant(tenant);
    ParamUtils.checkParam(dataId, group, "datumId", content);
    ParamUtils.checkParam(tag);
    Map<String, Object> configAdvanceInfo = new HashMap<String, Object>(10);
    MapUtil.putIfValNoNull(configAdvanceInfo, "config_tags", configTags);
    MapUtil.putIfValNoNull(configAdvanceInfo, "desc", desc);
    MapUtil.putIfValNoNull(configAdvanceInfo, "use", use);
    MapUtil.putIfValNoNull(configAdvanceInfo, "effect", effect);
    MapUtil.putIfValNoNull(configAdvanceInfo, "type", type);
    MapUtil.putIfValNoNull(configAdvanceInfo, "schema", schema);
    ParamUtils.checkParam(configAdvanceInfo);
    
    if (AggrWhitelist.isAggrDataId(dataId)) {
        LOGGER.warn("[aggr-conflict] {} attempt to publish single data, {}, {}", RequestUtil.getRemoteIp(request),
                dataId, group);
        throw new NacosException(NacosException.NO_RIGHT, "dataId:" + dataId + " is aggr");
    }
    
    final Timestamp time = TimeUtils.getCurrentTime();
    String betaIps = request.getHeader("betaIps");
    ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content);
    configInfo.setType(type);
    if (StringUtils.isBlank(betaIps)) {
        if (StringUtils.isBlank(tag)) {
            persistService.insertOrUpdate(srcIp, srcUser, configInfo, time, configAdvanceInfo, false);
            ConfigChangePublisher
                    .notifyConfigChange(new ConfigDataChangeEvent(false, dataId, group, tenant, time.getTime()));
        } else {
            persistService.insertOrUpdateTag(configInfo, tag, srcIp, srcUser, time, false);
            ConfigChangePublisher.notifyConfigChange(
                    new ConfigDataChangeEvent(false, dataId, group, tenant, tag, time.getTime()));
        }
    } else {
        // beta publish
        persistService.insertOrUpdateBeta(configInfo, betaIps, srcIp, srcUser, time, false);
        ConfigChangePublisher
                .notifyConfigChange(new ConfigDataChangeEvent(true, dataId, group, tenant, time.getTime()));
    }
    ConfigTraceService
            .logPersistenceEvent(dataId, group, tenant, requestIpApp, time.getTime(), InetUtils.getSelfIP(),
                    ConfigTraceService.PERSISTENCE_EVENT_PUB, content);
    return true;
}