Nacos源码 (4) 配置中心

这篇具有很好参考价值的文章主要介绍了Nacos源码 (4) 配置中心。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

本文阅读nacos-2.0.2的config源码,编写示例,分析推送配置、监听配置的原理。

客户端

创建NacosConfigService对象

Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.SERVER_ADDR, NACOS_HOST);
NacosConfigService configService = new NacosConfigService(properties);

构造方法:

public NacosConfigService(Properties properties) throws NacosException {
    ValidatorUtils.checkInitParam(properties);
    
    initNamespace(properties);
    this.configFilterChainManager = new ConfigFilterChainManager(properties);
    ServerListManager serverListManager = new ServerListManager(properties);
    serverListManager.start();
    
    this.worker = new ClientWorker(this.configFilterChainManager, serverListManager, properties);
    // will be deleted in 2.0 later versions
    agent = new ServerHttpAgent(serverListManager);
}
  1. 创建ConfigFilterChainManager - 过滤器链
  2. 创建ServerListManager - 服务器列表管理
  3. 创建ClientWorker - 用来发送请求,内部封装了一个ConfigRpcTransportClient类型对象agent,它能够获取到RpcClient与服务端进行通信

推送配置

Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.SERVER_ADDR, NACOS_HOST);

NacosConfigService configService = new NacosConfigService(properties);

StringWriter out = new StringWriter();
properties.store(out, "test config");

// 推送配置到nacos服务器
configService.publishConfig(
    ORDER_SERVICE, Constants.DEFAULT_GROUP, out.toString(), "properties");

推送配置到nacos服务器:

public boolean publishConfig(String dataId,
                             String group,
                             String content,
                             String type) throws NacosException {
    return publishConfigInner(namespace, dataId, group, null, null, null, content, type, null);
}

private boolean publishConfigInner(String tenant, String dataId, String group, String tag, String appName,
        String betaIps, String content, String type, String casMd5) throws NacosException {
    group = blank2defaultGroup(group);
    ParamUtils.checkParam(dataId, group, content);

    ConfigRequest cr = new ConfigRequest();
    cr.setDataId(dataId);
    cr.setTenant(tenant);
    cr.setGroup(group);
    cr.setContent(content);
    cr.setType(type);
    configFilterChainManager.doFilter(cr, null);
    content = cr.getContent();
    String encryptedDataKey = (String) cr.getParameter("encryptedDataKey");

    return worker.publishConfig(
        dataId, group, tenant, appName, tag, betaIps, content, encryptedDataKey, casMd5, type);
}

worker使用agent推送配置:

// 1. 封装ConfigPublishRequest对象
ConfigPublishRequest request = new ConfigPublishRequest(dataId, group, tenant, content);
request.setCasMd5(casMd5);
request.putAdditionalParam(TAG_PARAM, tag);
request.putAdditionalParam(APP_NAME_PARAM, appName);
request.putAdditionalParam(BETAIPS_PARAM, betaIps);
request.putAdditionalParam(TYPE_PARAM, type);
request.putAdditionalParam(ENCRYPTED_DATA_KEY_PARAM, encryptedDataKey);
// 2. 获取RpcClient对象
// 3. 使用RpcClient发请求
ConfigPublishResponse response = (ConfigPublishResponse) requestProxy(getOneRunningClient(), request);

监听配置

Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.SERVER_ADDR, NACOS_HOST);

NacosConfigService configService = new NacosConfigService(properties);

// 添加监听器
configService.addListener(ORDER_SERVICE, Constants.DEFAULT_GROUP, new AbstractListener() {
  @Override
  public void receiveConfigInfo(String configInfo) {
    System.out.printf(">> config: \n%s\n\n", configInfo);
  }
});
  1. 将监听器注册到本地,本地使用CacheData作为监听器管理器,封装配置名、dataId和监听器集合,内部使用CopyOnWriteArrayList保存监听器,如果是第一次监听,会先拉取一次配置。本地注册表为Map结构,使用dataId+group+tenant作为key,value是CacheData对象
  2. 在client初始化阶段,会注册一个ServerRequestHandler,专门处理服务器端的ConfigChangeNotifyRequest请求,该请求只会推送变化了的配置的基本信息,而不包括内容,所以此处还会触发一次ConfigBatchListenRequest请求
  3. 之后查找到变化的配置后,再发一个查询请求拉取配置

服务端

推送配置处理器

ConfigPublishRequestHandler处理器

配置中心使用ConfigPublishRequestHandler类处理客户端配置推送请求:

  1. 验证请求参数

  2. 封装configAdvanceInfo配置扩展信息

  3. 创建ConfigInfo封装配置信息

  4. 使用持久层对象insert或者update配置

  5. 使用ConfigChangePublisher推送一个ConfigDataChangeEvent事件

    ConfigChangePublisher.notifyConfigChange(
        new ConfigDataChangeEvent(false, dataId, group, tenant, time.getTime()));
    

ConfigDataChangeEvent事件处理

ConfigDataChangeEvent事件会触发数据dump操作和集群同步操作。

此处先介绍数据dump操作:

dumpService.dump(syncRequest.getDataId(), syncRequest.getGroup(), syncRequest.getTenant(),
    syncRequest.getTag(), syncRequest.getLastModified(), NetUtils.localIP());

dumpService是Dump data service用于备份数据:

// Add DumpTask to TaskManager, it will execute asynchronously.
public void dump(String dataId, String group, String tenant, String tag, long lastModified, String handleIp,
        boolean isBeta) {
    String groupKey = GroupKey2.getKey(dataId, group, tenant);
    String taskKey = String.join("+", dataId, group, tenant, String.valueOf(isBeta), tag);
    // 推送一个DumpTask
    dumpTaskMgr.addTask(taskKey, new DumpTask(groupKey, tag, lastModified, handleIp, isBeta));
}

DumpTask将使用DumpProcessor类处理:

  1. 把数据写到磁盘
  2. 推送LocalDataChangeEvent事件

LocalDataChangeEvent事件会被以下几个类处理:

  • LongPollingService$1会触发DataChangeTask,响应长轮询订阅者
  • RpcConfigChangeNotifier将数据变化推送给rpc订阅者
  • InternalConfigChangeNotifier处理内部配置文件变化

监听配置处理器

ConfigChangeBatchListenRequestHandler处理器

处理客户端的配置监听请求:文章来源地址https://www.toymoban.com/news/detail-662464.html

public class ConfigChangeBatchListenRequestHandler
        extends RequestHandler<ConfigBatchListenRequest, ConfigChangeBatchListenResponse> {

    @Autowired
    private ConfigChangeListenContext configChangeListenContext;

    @TpsControl(pointName = "ConfigListen")
    @Secured(action = ActionTypes.READ, parser = ConfigResourceParser.class)
    public ConfigChangeBatchListenResponse handle(
            ConfigBatchListenRequest configChangeListenRequest, RequestMeta meta)
            throws NacosException {
        String connectionId = StringPool.get(meta.getConnectionId());
        String tag = configChangeListenRequest.getHeader(Constants.VIPSERVER_TAG);

        ConfigChangeBatchListenResponse configChangeBatchListenResponse = 
            new ConfigChangeBatchListenResponse();
        for (ConfigBatchListenRequest.ConfigListenContext listenContext : configChangeListenRequest
                .getConfigListenContexts()) {
            String groupKey = GroupKey2
                    .getKey(listenContext.getDataId(), listenContext.getGroup(), listenContext.getTenant());
            groupKey = StringPool.get(groupKey);

            String md5 = StringPool.get(listenContext.getMd5());

            // 监听
            if (configChangeListenRequest.isListen()) {
                // 注册监听器,维护groupKey->connectionId集关系和groupKey->md5关系
                configChangeListenContext.addListen(groupKey, md5, connectionId);
                // 判断变化
                boolean isUptoDate = ConfigCacheService.isUptodate(groupKey, md5, meta.getClientIp(), tag);
                if (!isUptoDate) {
                    // 把变化的配置基本信息添加到响应
                    configChangeBatchListenResponse
                        .addChangeConfig(listenContext.getDataId(), listenContext.getGroup(),
                            listenContext.getTenant());
                }
            } else {
                // 取消监听
                configChangeListenContext.removeListen(groupKey, connectionId);
            }
        }

        return configChangeBatchListenResponse;
    }
}

到了这里,关于Nacos源码 (4) 配置中心的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Nacos源码 (4) 配置中心

    本文阅读nacos-2.0.2的config源码,编写示例,分析推送配置、监听配置的原理。 构造方法: 创建ConfigFilterChainManager - 过滤器链 创建ServerListManager - 服务器列表管理 创建ClientWorker - 用来发送请求,内部封装了一个ConfigRpcTransportClient类型对象agent,它能够获取到RpcClient与服务端进行

    2024年02月12日
    浏览(21)
  • 记录一次SpringBoot3+Nacos Config做配置中心时,No spring.config.import property has been defined的问题

    以下为报错信息: No spring.config.import property has been defined 启动时,控制台已经很明确的给出了一个标准的解决方案: Add a spring.config.import=nacos: property to your configuration. If configuration is not required add spring.config.import=optional:nacos: instead. To disable this check, set spring.cloud.nacos.config.import

    2024年02月11日
    浏览(40)
  • springcloud/springboot集成NACOS 做注册和配置中心以及nacos源码分析

    Spring Cloud 是一系列框架的有序集合如服务发现注册、配置中心、消息总线、负载均衡、熔断器、数据监控等。 SpringCloud 将多个服务框架组合起来,通过Spring Boot进行再封装,屏蔽掉了复杂的配置和实现原理,最终给开发者提供了一套简单易懂、易部署和易维护的分布式系统开

    2024年02月08日
    浏览(48)
  • 九、Nacos源码系列:Nacos配置中心原理(一)- SpringCloud应用启动时拉取配置

    熟悉Spring的小伙伴都知道,Spring 提供了强大的扩展机制。其中包括 ** ApplicationContextInitializer **,该扩展是在上下文准备阶段(prepareContext), 容器刷新之前做一些初始化工作 ,比如我们常用的配置中心 client 基本都是继承该初始化器,在容器刷新前将配置从远程拉到本地,然

    2024年02月19日
    浏览(43)
  • 解决 Spring Cloud 2021.0.5 版本,使用 nacos 做配置中心,报 No spring.config.import property has been defined 的问题

    报错信息如下 Description: No spring.config.import property has been defined Spring 官方给出的解决方案如下 Add a spring.config.import=nacos: property to your configuration. If configuration is not required add spring.config.import=optional:nacos: instead. To disable this check, set spring.cloud.nacos.config.import-check.enabled=false. 这里只

    2024年02月11日
    浏览(43)
  • alibabacloud的简单使用,nacos配置中心+服务中心。作者直接给自己写的源码

    nacos的图形化配置简单使用 SpringBoot版本和com.alibaba.cloud版本需要对应,不然会程序会启动失败 作者使用的版本 配置文件的id如果带文件类型,该文件类型最好和内部的格式一致,不然容易错误 没事不要使用多种格式的配置文件,出错的时候,贼难排查 Spring cloud alibaba 版本对

    2024年02月10日
    浏览(36)
  • 微服务 Spring Cloud 7,Nacos配置中心的Pull原理,附源码

    大家好,我是哪吒。 在单体服务时代,关于配置信息,管理一套配置文件即可。 而拆分成微服务之后,每一个系统都会有自己的配置,并且都各不相同,有些配置还需要动态改变,以达到动态降级、切流量、扩缩容等目的。 在Spring Boot开发中,可以把配置项放到config文件中

    2024年02月04日
    浏览(42)
  • Nacos Config--服务配置

    Nacos Config--服务配置基于网关,网关详情请见下方链接 http://t.csdn.cn/A8R4Y http://t.csdn.cn/A8R4Y 首先我们来看一下 , 微服务架构下关于 配置文件 的一些问题: 1. 配置文件相对分散。在一个微服务架构下,配置文件会随着微服务的增多变的 越来越多 ,而且分散在各个微服务中,不

    2023年04月22日
    浏览(34)
  • Nacos配置中心中配置文件的创建、微服务读取nacos配置中心

    在企业项目中会有非常多的服务,不同的开发环境还有不同的配置文件,所以就导致配置文件非常多。 那么肯定就会有一些公共配置,多个服务都是使用过一样的,那么就可以使用配置中心来进行统一管理,避免修改一个配置项要去各个服务都改一遍。 使用传统方式的配置

    2024年02月02日
    浏览(30)
  • Nacos源码 (3) 注册中心

    本文将从一个服务注册示例入手,通过阅读客户端、服务端源码,分析服务注册、服务发现原理。 使用的2.0.2的版本。 NacosNamingService提供两个构造方法: 第二个方法的properties的key在PropertyKeyConst常量类可以找到,如: namespace username password serverAddr clusterName 其他 构造方法中会

    2024年02月13日
    浏览(24)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包