1. 配置信息的发布

    • 配置信息发布请求URL: POST: /v1/cs/configs
    • nacos在STANDALONE模式或集群模式没有指定用mysql情况下使用derby数据库,在集群模式且指定mysql情况下使用mysql
    • 持续化到数据库后立马同步集群中的其他节点
    /**
* 增加或更新非聚合数据。
*
* @throws NacosException
*/
@PostMapping
@Secured(action = ActionTypes.WRITE, parser = ConfigResourceParser.class)
public Boolean publishConfig(HttpServletRequest request, HttpServletResponse response,
@RequestParam("dataId") String dataId, @RequestParam("group") String group,
@RequestParam(value = "tenant", required = false, defaultValue = StringUtils.EMPTY)
String tenant,
@RequestParam("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 {
//省略参数验证代码
..................... //persistService.insertOrUpdate插入或更新数据库
//EventDispatcher.fireEvent 通知集群中其他节点
final Timestamp time = TimeUtils.getCurrentTime();
String betaIps = request.getHeader("betaIps");
ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content);
if (StringUtils.isBlank(betaIps)) {
if (StringUtils.isBlank(tag)) {
persistService.insertOrUpdate(srcIp, srcUser, configInfo, time, configAdvanceInfo, false);
EventDispatcher.fireEvent(new ConfigDataChangeEvent(false, dataId, group, tenant, time.getTime()));
} else {
persistService.insertOrUpdateTag(configInfo, tag, srcIp, srcUser, time, false);
EventDispatcher.fireEvent(new ConfigDataChangeEvent(false, dataId, group, tenant, tag, time.getTime()));
}
} else { // beta publish
persistService.insertOrUpdateBeta(configInfo, betaIps, srcIp, srcUser, time, false);
EventDispatcher.fireEvent(new ConfigDataChangeEvent(true, dataId, group, tenant, time.getTime()));
}
return true;
}
  • EventDispatcher.fireEvent 触发 AsyncNotifyService.onEvent事件
  • AsyncNotifyService.onEvent事件中遍历serverList通知集群各个节点
  • 如果某个节点不健康或同步失败延迟一段时间后重新通知:schedule(asyncTask, delay, TimeUnit.MILLISECONDS);

@Service
public class AsyncNotifyService extends AbstractEventListener { //onEvent事件遍历serverList通知集群各个节点
@Override
public void onEvent(Event event) {
// 并发产生 ConfigDataChangeEvent
if (event instanceof ConfigDataChangeEvent) {
ConfigDataChangeEvent evt = (ConfigDataChangeEvent) event;
long dumpTs = evt.lastModifiedTs;
String dataId = evt.dataId;
String group = evt.group;
String tenant = evt.tenant;
String tag = evt.tag;
List<?> ipList = serverListService.getServerList(); // 其实这里任何类型队列都可以
Queue<NotifySingleTask> queue = new LinkedList<NotifySingleTask>();
for (int i = 0; i < ipList.size(); i++) {
queue.add(new NotifySingleTask(dataId, group, tenant, tag, dumpTs, (String) ipList.get(i), evt.isBeta));
}
EXECUTOR.execute(new AsyncTask(httpclient, queue));
}
} // 同步任务逻辑
class AsyncTask implements Runnable {
@Override
public void run() {
executeAsyncInvoke();
} private void executeAsyncInvoke() {
while (!queue.isEmpty()) {
NotifySingleTask task = queue.poll();
String targetIp = task.getTargetIP();
if (serverListService.getServerList().contains(
targetIp)) {
// 启动健康检查且有不监控的ip则直接把放到通知队列,否则通知
if (serverListService.isHealthCheck() && ServerListService.getServerListUnhealth().contains(targetIp)) {
// target ip 不健康,则放入通知列表中
// get delay time and set fail count to the task
// schedule(asyncTask, delay, TimeUnit.MILLISECONDS);
asyncTaskExecute(task);
} else {
// /v1/cs/communication/dataChange?dataId={2}&group={3}
HttpGet request = new HttpGet(task.url);
request.setHeader(NotifyService.NOTIFY_HEADER_LAST_MODIFIED, String.valueOf(task.getLastModified()));
request.setHeader(NotifyService.NOTIFY_HEADER_OP_HANDLE_IP, LOCAL_IP);
httpclient.execute(request, new AsyncNotifyCallBack(httpclient, task));
}
}
}
}
} class AsyncNotifyCallBack implements FutureCallback<HttpResponse> {
// 同步其他节点失败
@Override
public void failed(Exception ex) {
long delayed = System.currentTimeMillis() - task.getLastModified();
//get delay time and set fail count to the task
//延迟一段时间后重新通知
//schedule(asyncTask, delay, TimeUnit.MILLISECONDS);
asyncTaskExecute(task);
MetricsMonitor.getConfigNotifyException().increment();
}
} }
  1. 配置信息的获取
  • 读取配置信息的时候加读锁

    1. lockResult>0 加锁成功,获取配置信息后返回HttpServletResponse.SC_OK 或 HttpServletResponse.SC_NOT_FOUND
    2. lockResult==0对应的配置信息不存在返回 HttpServletResponse.SC_NOT_FOUND
    3. lockResult<0 已有线程加了写锁返回 HttpServletResponse.SC_CONFLICT
  • 单机且不用mysql情况下从数据库中获取,其他配置从文件中获取配置信息(本地文件相当于mysql的缓存)

@Service
public class ConfigServletInner {
/**
* 同步配置获取接口
*/
public String doGetConfig(HttpServletRequest request, HttpServletResponse response, String dataId, String group,
String tenant, String tag, String clientIp) throws IOException, ServletException { int lockResult = tryConfigReadLock(groupKey);
if (lockResult > 0) {
//代码挺多总体逻辑归纳如下
//单机且不用mysql情况下从数据库中获取,其他配置从文件中获取配置信息
//数据库情况下判断从config_info,还是config_info_beta,还是config_info_tag表获取数据
//文件情况下判断从还是BASE_DIR还是BETA_DIR,还是TAG_DIR目录获取配置文件
//本地文件获取比mysql中获取更快,本地文件相当于mysql的缓存
}
}
}

为了查询效率,mysql中的数据缓存到每个集群节点的文件中,缓存时机有3中情况

  • 当nacos启动的时候如果当前时间距离最后一次心跳时间超过6个小时,则全量缓存mysql数据
  • 启动定时任务每6个小时重新全量缓存mysql数据
  • @GetMapping("/dataChange")时处理单个数据
 //@PostConstruct init() 调用 dumpConfigInfo
private void dumpConfigInfo(DumpAllProcessor dumpAllProcessor) throws IOException {
int timeStep = 6;
Boolean isAllDump = true;
// initial dump all
FileInputStream fis = null;
Timestamp heartheatLastStamp = null;
try {
if (isQuickStart()) {
File heartbeatFile = DiskUtil.heartBeatFile();
if (heartbeatFile.exists()) {
fis = new FileInputStream(heartbeatFile);
String heartheatTempLast = IoUtils.toString(fis, Constants.ENCODE);
heartheatLastStamp = Timestamp.valueOf(heartheatTempLast);
//当前时间距离最后一次心跳时间超过6个小时
if (TimeUtils.getCurrentTime().getTime() - heartheatLastStamp.getTime() < timeStep * 60 * 60 * 1000) {
isAllDump = false;
}
}
}
if (isAllDump) {
LogUtil.defaultLog.info("start clear all config-info.");
DiskUtil.clearAll();
//
dumpAllProcessor.process(DumpAllTask.TASK_ID, new DumpAllTask());
}
} catch (IOException e) {
LogUtil.fatalLog.error("dump config fail" + e.getMessage());
throw e;
}
}
 @PostConstruct
public void init() {
//启动定时任务定时缓存数据
TimerTaskService.scheduleWithFixedDelay(dumpAll, initialDelay, DUMP_ALL_INTERVAL_IN_MINUTE, TimeUnit.MINUTES);
}
   /**
* 通知配置信息改变
*/
@GetMapping("/dataChange")
public Boolean notifyConfigInfo(HttpServletRequest request,
@RequestParam("dataId") String dataId, @RequestParam("group") String group,
@RequestParam(value = "tenant", required = false, defaultValue = StringUtils.EMPTY)
String tenant,
@RequestParam(value = "tag", required = false) String tag) {
dataId = dataId.trim();
group = group.trim();
String lastModified = request.getHeader(NotifyService.NOTIFY_HEADER_LAST_MODIFIED);
long lastModifiedTs = StringUtils.isEmpty(lastModified) ? -1 : Long.parseLong(lastModified);
String handleIp = request.getHeader(NotifyService.NOTIFY_HEADER_OP_HANDLE_IP);
String isBetaStr = request.getHeader("isBeta");
//其他节点通知变更后缓存数据
if (StringUtils.isNotBlank(isBetaStr) && trueStr.equals(isBetaStr)) {
dumpService.dump(dataId, group, tenant, lastModifiedTs, handleIp, true);
} else {
dumpService.dump(dataId, group, tenant, tag, lastModifiedTs, handleIp);
}
return true;
}
  1. 配置信息的轮询

nacos配置中心之服务器端的更多相关文章

  1. SpringBoot使用Nacos配置中心

    本文介绍SpringBoot如何使用阿里巴巴Nacos做配置中心. 1.Nacos简介 Nacos是阿里巴巴集团开源的一个易于使用的平台,专为动态服务发现,配置和服务管理而设计.它可以帮助您轻松构建云 ...

  2. Nacos配置中心

    本文介绍spring cloud 集成 nacos案例 官方文档:https://nacos.io/zh-cn/docs/what-is-nacos.html](https://nacos.io/zh ...

  3. Spring Cloud 系列之 Alibaba Nacos 配置中心

    Nacos 介绍 Nacos 是 Alibaba 公司推出的开源工具,用于实现分布式系统的服务发现与配置管理.英文全称 Dynamic Naming and Configuration Service ...

  4. Nacos配置中心使用

    在系统开发过程中,开发者通常会将一些需要变更的参数.变量等从代码中分离出来独立管理,以独立的配置文件的形式存在.目的是让静态的系统工件或者交付物(如 WAR,JAR 包等)更好地和实际的物理运行环境进 ...

  5. 微服务从nacos配置中心获得配置信息

    一,安装nacos, 略 二,创建父工程和微服务工程 service1, service2,以idea为例 1, new -> project -> Maven -> 填写group ...

  6. Nacos配置中心和服务的注册发现

    在上一篇中,我们已经把Nacos的集群搭建好了,那么既然已经搭建好了,就要在咱们的项目中去使用.Nacos既可以做配置中心,也可以做注册中心.我们先来看看在项目中如何使用Nacos做配置中心. Nac ...

  7. Spring Cloud Config、Apollo、Nacos配置中心选型及对比

    Spring Cloud Config.Apollo.Nacos配置中心选型及对比 1.Nacos 1.1 Nacos主要提供以下四大功能 2.Spring Cloud Config 3.Apollo ...

  8. Spring Cloud Alibaba(5)---Nacos(配置中心)

    Nacos(配置中心) 有关Spring Cloud Alibaba之前写过四篇文章,这篇也是在上面项目的基础上进行开发. Spring Cloud Alibaba(1)---入门篇 Spring C ...

  9. 【Nacos】Springboot整合Nacos配置中心(二) 多环境配置

    本篇随笔接上一篇文章:Springboot整合Nacos配置中心(一),主要记录Nacos多环境的配置的方法 Nacos多环境的配置 方法一: 1.在项目中的bootstrap.yaml文件中配置激活 ...

随机推荐

  1. EF6.2加载速度慢的解决方案

    最近的项目中一直有反馈,EF在第一次启动之后调用的话,加载速度很慢,在网上搜索了一下,基本就是三种解决方案. 在程序启动的时候将映射视图缓存下来. 使用Ngen生成EF的本地镜像. IIS8内置功能 ...

  2. PAT甲级—暴力搜索

    1091 Acute Stroke (30point(s)) 基础的搜索,但是直接用递归会导致段错误,改用队列之后就不会了,这说明递归调用在空间利用率上还是很吃亏的. #include <cst ...

  3. 【bzoj 3232】圈地游戏(算法效率--01分数规划+图论--最小割)

    题目:DZY家的后院有一块地,由N行M列的方格组成,格子内种的菜有一定的价值,并且每一条单位长度的格线有一定的费用.DZY喜欢在地里散步.他总是从任意一个格点出发,沿着格线行走直到回到出发点,且在行走 ...

  4. P1387 最大正方形 && P1736 创意吃鱼法(DP)

    题目描述 在一个n*m的只包含0和1的矩阵里找出一个不包含0的最大正方形,输出边长. 输入输出格式 输入格式: 输入文件第一行为两个整数n,m(1<=n,m<=100),接下来n行,每行m ...

  5. codeforces626E.Simple Skewness(三分)

    Define the simple skewness of a collection of numbers to be the collection's mean minus its median. ...

  6. Codeforces Round #669 (Div. 2) C. Chocolate Bunny (交互,构造)

    题意:有一个长度为\(n\)的隐藏序列,你最多可以询问\(2n\)次,每次可以询问\(i\)和\(j\)位置上\(p[i]\ mod\ p[j]\)的结果,询问的格式是\(?\ x\ y\),如果已经 ...

  7. Nacos学习与实战

    1. 什么是Nacos 官网:https://nacos.io/zh-cn/index.html Nacos是阿里巴巴集团开源的项目,Nacos 致力于帮助您发现.配置和管理微服务. Nacos提供了 ...

  8. 牛客网多校第3场 C-shuffle card 【splay伸展树】

    题目链接:戳这里 转自:戳这里 关于splay入门:戳这里 题意:给n个数,进行m次操作,每次都从n个数中取出连续的数放在最前面. 解题思路:splay的区间操作. 附代码: 1 #include&l ...

  9. Ubuntu 18.04 + pip3 install virtualenvwrapper 找不到virtualenvwrapper.sh

    Reference Ubuntu 18.04 只自带python3.6.5, 因此不想装python2了, 但通过apt install 装virtualenvwrapper时发现必须得装python ...

  10. Lenet车牌号字符识别+保存模型

    # 部分函数请参考前一篇或后一篇文章 import tensorflow as tf import tfrecords2array import numpy as np import matplotl ...