如果你的服务已经能正常跑起来,个人建议可以先感受下nacos的魅力,也就是怎么使用吧

直接上代码

@Controller
@NacosPropertySource(dataId = "springboot2-nacos-config", autoRefreshed = true)
public class HealthController { @NacosValue(value = "${nacos.test.propertie:123}", autoRefreshed = true)
private String testProperties; @ResponseBody
@GetMapping("/nacos/test")
public String test(){
return testProperties;
} @ResponseBody
@RequestMapping(value = "/readiness", method = RequestMethod.GET)
public Object readiness(HttpServletRequest request) {
boolean isConfigReadiness = true;
boolean isNamingReadiness = false; if (isConfigReadiness && isNamingReadiness) {
return ResponseEntity.ok().body("OK");
} if (!isConfigReadiness && !isNamingReadiness) {
return ResponseEntity.status(500).body("Config and Naming are not in readiness");
} if (!isConfigReadiness) {
return ResponseEntity.status(500).body("Config is not in readiness");
} return ResponseEntity.status(500).body("Naming is not in readiness");
}
}

我们直接用postman请求下,直接返回结果了,

我们在nacos中的相关配置如下:

这样我就很方便的把我们需要的值取过来了,而且不是通过DB,cache方式获取,而是在远程nacos中配置,我们能够实时获取的到;

那么问题就来了,nacos是怎么做到的呢,当然nacos的功能远不止于此;

我们就根据这个作为一个最直观的入口,跟下代码:

在nacos中发布的操作

找代码v1/cs/configs,当然再试的时候可以找V1/CS

Constants.java
    
public static final String BASE_PATH = "/v1/cs";
public static final String CONFIG_CONTROLLER_PATH = BASE_PATH + "/configs";
/**
* 增加或更新非聚合数据。
*
* @throws NacosException
*/
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
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 {
final String srcIp = RequestUtil.getRemoteIp(request);
String requestIpApp = RequestUtil.getAppName(request);
// 参数校验
ParamUtils.checkParam(dataId, group, "datumId", content);
ParamUtils.checkParam(tag); Map<String, Object> configAdvanceInfo = new HashMap<String, Object>(10);
if (configTags != null) {
configAdvanceInfo.put("config_tags", configTags);
}
if (desc != null) {
configAdvanceInfo.put("desc", desc);
}
if (use != null) {
configAdvanceInfo.put("use", use);
}
if (effect != null) {
configAdvanceInfo.put("effect", effect);
}
if (type != null) {
configAdvanceInfo.put("type", type);
}
if (schema != null) {
configAdvanceInfo.put("schema", schema);
}
ParamUtils.checkParam(configAdvanceInfo);
// 白名单
if (AggrWhitelist.isAggrDataId(dataId)) {
log.warn("[aggr-conflict] {} attemp 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);

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()));
}
ConfigTraceService.logPersistenceEvent(dataId, group, tenant, requestIpApp, time.getTime(),
LOCAL_IP, ConfigTraceService.PERSISTENCE_EVENT_PUB, content); return true;
}

就从这个controller去做分析,其实核心一下就能看出来就是一个insertOrUpdate,一个fireEvent;

insertorUpdate这个nacos没有用mybatis、hibernate这些ORM框架(减少依赖耦合吧);

下方高能!!!!!!!!!!!!!!!!!!!!!!!!!!

直接用jdbcTemblate就行数据插入,大家在进行debug的时候注意下,jdbcTemplate中有个事务超时时间,

nacos中有两种模板,

 private JdbcTemplate jt;
private TransactionTemplate tjt;

这个他都设置了默认超时时间(还有另外一个地方一个3秒一个5秒,建议大家在DEBUG的时候把这个时间调大一点,300,,500^_^)

BasicDataSourceServiceImpl.java
 @PostConstruct
public void init() {
queryTimeout = NumberUtils.toInt(System.getProperty("QUERYTIMEOUT"), 300);
jt = new JdbcTemplate();
/**
* 设置最大记录数,防止内存膨胀
*/
jt.setMaxRows(50000);
jt.setQueryTimeout(queryTimeout); testMasterJT = new JdbcTemplate();
testMasterJT.setQueryTimeout(queryTimeout); testMasterWritableJT = new JdbcTemplate();
/**
* 防止login接口因为主库不可用而rt太长
*/
testMasterWritableJT.setQueryTimeout(1);
/**
* 数据库健康检测
*/
testJTList = new ArrayList<JdbcTemplate>();
isHealthList = new ArrayList<Boolean>(); tm = new DataSourceTransactionManager();
tjt = new TransactionTemplate(tm);
/**
* 事务的超时时间需要与普通操作区分开
*/
tjt.setTimeout(TRANSACTION_QUERY_TIMEOUT);
if (!STANDALONE_MODE || PropertyUtil.isStandaloneUseMysql()) {
try {
reload();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(DB_LOAD_ERROR_MSG);
} TimerTaskService.scheduleWithFixedDelay(new SelectMasterTask(), 10, 10,
TimeUnit.SECONDS);
TimerTaskService.scheduleWithFixedDelay(new CheckDBHealthTask(), 10, 10,
TimeUnit.SECONDS);
}
}

看下config_info的表结构,他这边判断更新的依据就是直接插入,

捕获唯一索引的异常,data_id+group+tenant重复的话就会抛出异常,捕获这个异常进行更新操作!

表结构

persistService.insertOrUpdate
 /**
* 写入主表,插入或更新
*/
public void insertOrUpdate(String srcIp, String srcUser, ConfigInfo configInfo, Timestamp time,
Map<String, Object> configAdvanceInfo, boolean notify) {
try {
addConfigInfo(srcIp, srcUser, configInfo, time, configAdvanceInfo, notify);
} catch (DataIntegrityViolationException ive) { // 唯一性约束冲突
updateConfigInfo(configInfo, srcIp, srcUser, time, configAdvanceInfo, notify);
}
}

后面就是最核心的地方了

EventDispatcher.fireEvent(new ConfigDataChangeEvent(false, dataId, group, tenant, time.getTime()));

通过event的dispatcher,进行相应的操作,这个就是观察者模式的体现,Apollo中也有类似的操作;

篇幅过长,这里就不再追加了,看下一篇吧^_^

Nacos深入浅出(二)的更多相关文章

  1. java代理的深入浅出(二)-CGLIB

    java代理的深入浅出(二)-CGLIB 1.基本原理 CGLIB的原理就是生成一个要代理类的子类,子类重写要代理的类的所有不是final的方法.在子类中拦截所有父类方法的调用,拦截下来交给设置的Me ...

  2. 02-Unity深入浅出(二)

    一. Unity声明周期 Unity容器为我们提供了6种生命周期,便于我们根据项目需求来选择使用. (1). 瞬时.默认省略即为瞬时,无论单线程还是多线程,每次都重新创建对象.new Transien ...

  3. Nacos深入浅出(十)

    基本上到第9篇,整个请求的一套就结束了,感觉这里跳跳绕绕很多东西,下面我们来做个总结:从Nacos配置平台修改,到Client请求更新,事件触发去取值返回给客户端,整个过程感觉只分析到了4.5层的深度 ...

  4. Nacos深入浅出(九)

    然而Nacos的发布操作并不是上面我们想的那样通过代理去实现,通过下面的代码我们分析下: public class NacosConfigurationPropertiesBindingPostPro ...

  5. Nacos深入浅出(八)

    Nacos-spring-context.java 感觉这个后台要比之前的Nacos复杂多了,涉及到很多基础的概念,慢慢看,这个后面慢慢更新解析过程 看到他的目录结构一个是基于注解,一个是XML的解析 ...

  6. Nacos深入浅出(七)

    大家可以把这个也下载下来,结合之前的Nacos一起来看下,感觉前面几篇看了好像冰山一角的感觉 学无止境! https://github.com/nacos-group/nacos-spring-pro ...

  7. Nacos深入浅出(六)

    其实我们发现在我们本地新生成了文件,这个文件就是nacos; 这个文件怎么那么眼熟,不就是我们的controller中的注解里面的参数value么: @Controller @NacosPropert ...

  8. Nacos深入浅出(五)

    四中标色的代码 result = ConfigService.dump(dataId, group, tenant, cf.getContent(), lastModified); 我们看下这个方法 ...

  9. Nacos深入浅出(四)

    private void executeAsyncInvoke() { while (!queue.isEmpty()) { NotifySingleTask task = queue.poll(); ...

随机推荐

  1. ManualResetEvent使用

    1.定义 MSDN定义: 通知一个或多个正在等待的线程已发生事件.此类不能被继承. 详细说明: ManualResetEvent 允许线程通过发信号互相通信.通常,此通信涉及一个线程在其他线程进行之前 ...

  2. POJ1226 Substrings ——后缀数组 or 暴力+strstr()函数 最长公共子串

    题目链接:https://vjudge.net/problem/POJ-1226 Substrings Time Limit: 1000MS   Memory Limit: 10000K Total ...

  3. Spring Boot2.0之性能优化

    1.JVM参数调优   针对运行效果  吞吐量    初始堆内存与最大堆尽量相同   减少垃圾回收次数  2.扫包优化: 启动优化 默认Tomcat容器改为Undertow Tomcat的吞吐量500 ...

  4. python注释行与段落

    注释行:# 注释段:‘’‘   ’‘’

  5. hdmap相关单词

    交叉口(junction) 交叉口组(junctiongroup)

  6. CC通信软件list

    bozokgh0stnanocoredarkcometponydarkcometadwindadzokaecomblacknixbluebananacorigaratdarkcometDRAThuig ...

  7. resEdit

    resEdit:一个图形界面编辑工具,它不但可以用来编写程序所图形界面(如修改图标.菜单.鼠标.版本信息等),还支持了对exe.dll等执行文件内的资源(图标.菜单.鼠标指针.位图.版本信息)等进行修 ...

  8. 0.5px的实现的几种方法

    方法一 通过css3缩放 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...

  9. zero to one (4)

    复盘--天下武功唯快不破 There is no martial art is indefectible, while the fastest speed is the only way for lo ...

  10. Virtual Codeforces Round #392 (Div. 2)

    下午闲来无事开了一场Virtual participation 2h就过了3道水题...又跪了..这只是Div. 2啊!!! 感觉这次直接就是跪在了读题上,T1,T2读题太慢,T3还把题读错了 要是让 ...