前端技术
HTML
CSS
Javascript
前端框架和UI库
VUE
ReactJS
AngularJS
JQuery
NodeJS
JSON
Element-UI
Bootstrap
Material UI
服务端和客户端
Java
Python
PHP
Golang
Scala
Kotlin
Groovy
Ruby
Lua
.net
c#
c++
后端WEB和工程框架
SpringBoot
SpringCloud
Struts2
MyBatis
Hibernate
Tornado
Beego
Go-Spring
Go Gin
Go Iris
Dubbo
HessianRPC
Maven
Gradle
数据库
MySQL
Oracle
Mongo
中间件与web容器
Redis
MemCache
Etcd
Cassandra
Kafka
RabbitMQ
RocketMQ
ActiveMQ
Nacos
Consul
Tomcat
Nginx
Netty
大数据技术
Hive
Impala
ClickHouse
DorisDB
Greenplum
PostgreSQL
HBase
Kylin
Hadoop
Apache Pig
ZooKeeper
SeaTunnel
Sqoop
Datax
Flink
Spark
Mahout
数据搜索与日志
ElasticSearch
Apache Lucene
Apache Solr
Kibana
Logstash
数据可视化与OLAP
Apache Atlas
Superset
Saiku
Tesseract
系统与容器
Linux
Shell
Docker
Kubernetes
[数据节点 Data Node或Znode...]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
ZooKeeper
...ZooKeeper的节点负载均衡策略:深入理解与实战示例 在分布式系统中,ZooKeeper作为一种高可用、高性能且分布式的协调服务,为集群节点间的负载均衡提供了强大的支持。嘿,伙计,这篇东西啊,咱们要从理论的高山一步一步下到实战的平原,带你深入探访ZooKeeper节点负载均衡策略的那个神秘又精彩的领域。而且,咱还会掏出实例代码给你现场展示,让你亲身体验,实实在在地感受到这个策略有多大的魔力! 1. ZooKeeper基础及其在负载均衡中的作用 (1)首先,我们简要回顾一下ZooKeeper的基本概念。ZooKeeper,这个家伙可厉害了,它是个开源的分布式应用程序协调小能手。想象一下,你在管理一大群分布式应用程序时,就像在动物园里指挥各种动物协同完成任务一样,这时候ZooKeeper就扮演了那个神奇的驯兽师角色。它提供了一些超级实用的一致性小工具,比如分布式锁呀、队列呀、选举机制什么的,这样一来,甭管你的分布式环境多复杂,都能让这些程序宝宝们高效又稳定地一起愉快玩耍、共同工作啦! (2)在负载均衡场景下,ZooKeeper扮演了至关重要的角色。它能够像个小管家一样,时刻保管并更新集群里每个小节点的状态信息,确保这些数据都是鲜活、热乎的。客户端能够通过ZooKeeper这个小帮手,实时掌握各个节点的最新负载状况。这样一来,它就能像一个聪明的调度员,火眼金睛地做出最佳的服务请求转发方案,确保不同节点之间的活儿分配得均匀,实现工作负载的完美均衡。 2. ZooKeeper节点负载均衡策略详解 (1)数据节点(ZNode)管理 在ZooKeeper中,每个服务节点可以注册为一个ZNode,同时附带该节点的负载信息。例如,我们可以创建一个持久化的ZNode /services/serviceName/nodes/nodeId,并在其数据部分存储节点负载量。 java // 创建ZNode并设置节点负载数据 String path = "/services/serviceName/nodes/nodeId"; byte[] data = String.valueOf(nodeLoad).getBytes(StandardCharsets.UTF_8); zk.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); (2.)监听器(Watcher) 客户端可以通过在特定ZNode上设置Watcher,实时感知到节点负载信息的变化。一旦某个服务节点的负载发生变化,ZooKeeper会通知所有关注此节点的客户端。 java // 设置监听器,监控节点负载变化 Stat stat = new Stat(); byte[] data = zk.getData("/services/serviceName/nodes/nodeId", new Watcher() { @Override public void process(WatchedEvent event) { // 在这里处理节点负载变化事件 } }, stat); (3)选择最佳服务节点 基于ZooKeeper提供的最新节点负载数据,客户端可以根据预设的负载均衡算法(如轮询、最小连接数、权重分配等)来选择当前最合适的服务节点进行请求转发。 java List children = zk.getChildren("/services/serviceName/nodes", false); children.sort((node1, node2) -> { // 这里根据节点负载数据进行排序,选择最优节点 }); String bestNode = children.get(0); 3. 探讨与思考 运用ZooKeeper实现节点负载均衡的过程中,我们能够感受到它的灵活性与强大性。不过,到了实际用起来的时候,有几个挑战咱们也得留心一下。比如,怎么捣鼓出一个既聪明又给力的负载均衡算法,可不是件轻松事儿;再者,网络延迟这个磨人的小妖精怎么驯服,也够头疼的;还有啊,在大规模集群里头保持稳定运行,这更是个大大的考验。这就意味着我们得不断动手尝试、灵活应变,对策略进行微调和升级,确保把ZooKeeper这个分布式协调服务的大能耐,彻彻底底地发挥出来。 总结来说,ZooKeeper在节点负载均衡策略上的应用,既体现了其作为一个通用分布式协调框架的价值,又展示了其实现复杂分布式任务的能力。利用ZooKeeper那个相当聪明的数据模型和监听功能,咱们完全可以捣鼓出一个既能让业务跑得溜溜的,又能稳如磐石、始终保持高可用性的分布式系统架构。就像是用乐高积木搭建一座既美观又结实的大厦一样,我们借助ZooKeeper这块宝,来创建咱所需要的高性能系统。所以,在我们实实在在做开发的时候,要是能摸透并熟练运用ZooKeeper这家伙的节点负载均衡策略,那可是对提升我们系统的整体表现力有着大大的好处,这一点儿毋庸置疑。
2024-01-21 23:46:49
122
秋水共长天一色
ZooKeeper
...reate 方法创建节点,并设置 createMode 参数为 CreateMode.EPHEMERAL_SEQUENTIAL,这样创建的节点会自动删除,而不需要手动删除。这种方式可以避免因长时间未删除节点而导致的数据泄露问题。 下面是一个简单的示例: java try { ZooKeeper zk = new ZooKeeper("localhost:2181", 3000, new Watcher() { @Override public void process(WatchedEvent event) { System.out.println("Received watch event : " + event); } }); byte[] data = new byte[10]; String path = "/node"; try { zk.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } catch (IOException | KeeperException e) { e.printStackTrace(); } 在这个示例中,我们首先创建了一个 ZooKeeper 对象,并设置了超时时间为 3 秒钟。然后,我们创建了一个节点,并将节点的数据设置为 null。如果在创建过程中不小心遇到 InterruptedException 这个小插曲,我们会把当前线程的状态给恢复原状,然后抛出一个新的 RuntimeException,就像把一个突然冒出来的小麻烦重新打包成一个新异常扔出去一样。 五、总结 在 ZooKeeper 中,我们可以通过设置创建模式为 EPHEMERAL_SEQUENTIAL 来自动删除节点,从而避免因长时间未删除节点而导致的数据泄露问题。同时呢,咱们也得留意一下,得妥善处理那个 InterruptedException,可别小看了它,要是没整对的话,可能会让程序闹脾气直接罢工。
2023-05-26 10:23:50
114
幽谷听泉-t
ZooKeeper
...金会开发和维护。在大数据和分布式系统环境中,Zookeeper常用于提供配置管理、统一命名服务、集群选主、分布式锁等核心服务,通过其数据节点(Znode)和会话机制实现高一致性和可靠性。 数据节点(Data Node或Znode) , 在Zookeeper中,数据节点是存储数据的基本单元,每个数据节点都有一个唯一的路径标识符,并且可以包含数据和一组子节点。当应用程序尝试访问不存在或者因会话过期等原因而无法访问的数据节点时,就会出现“无法访问数据节点”的错误提示。 会话(Session) , 在Zookeeper中,客户端与服务器之间建立的一种持久连接被称为会话。会话允许客户端在一段时间内进行多次操作,期间服务器会保持客户端的状态信息。当会话超时或者网络故障导致客户端与服务器失去联系后,Zookeeper服务器会认为该会话已过期,并可能释放与之关联的数据节点资源,此时客户端再试图访问相关数据节点就会遇到“无法访问数据节点”的问题。
2023-02-03 19:02:33
77
青春印记-t
转载文章
...H5自定义属性 五.节点操作 1.为什么要学习节点操作 2.节点概述 3.节点层级 一.DOM简介 1.什么是DOM 文档对象模型(简称DOM) 是W3C组织推荐的处理可扩展标记语言的标准编程接口 W3C已经定义来一系列DOM接口,通过这些DOM接口可以改变网页的内容、结构样式。 2.DOM 树 文档:一个页面就是一个文档,DOM 中使用 document 表示 元素:页面中的所有标签都是元素,DOM 中使用 element 表示 节点:网页中的所有内容都是节点(标签、属性、文本、注释等),DOM 中使用 node 表示 文档树(Dom树):以html为根节点,形成的一颗倒立的树状结构,我们成为DOM树;这个树上所有的东西都叫节点,节点有很多类,比如文本节点,元素节点等等,这些节点如果我们通过DOM方法去获取或者其他的操作去使用就叫做DOM对象,所有节点都是DOM对象 二.获取元素的方法 1.获取页面中的元素可以使用以下几种方式 根据ID获取 根据标签名获取 通过HTML5新增的方法获取 特殊元素获取 1.根据ID获取 使用getElementByld()方法可以获取带有ID的元素对象 getElementByld(),是document下的一个方法 代码演示 <body><div id="time">2020-11-26</div><script>// 1.因为我们文档页面从上往下加载,所以先得有标签 所以我们的script写在标签下面// 2. document文档 get 获得 element 元素 by 通过 驼峰命名法// 3.参数 id是大小写敏感的字符串// 4.返回的是一个对象var timer = document.getElementById('time');console.log(timer);// 5.console.dir 打印我们返回得的元素对象 更好的查看里面的属性和方法console.dir(timer);</script></body> 2.根据标签名获取 使用getElementsByTagName()方法可以返回带有指定标签名的对象的集合 语法如下 document.getElementsByTagName('标签名') 注意: 1.因为得到的是一个对象的集合,使用我们想要操作里面的元素就需要遍历 得到元素对象是动态的 代码演示 <body><ul><li>我们的征程是星辰大海</li><li>我们的征程是星辰大海</li><li>我们的征程是星辰大海</li><li>我们的征程是星辰大海</li><li>我们的征程是星辰大海</li></ul><ul id="nav"><li>心存感恩,所遇皆美好~</li><li>心存感恩,所遇皆美好~</li><li>心存感恩,所遇皆美好~</li><li>心存感恩,所遇皆美好~</li><li>心存感恩,所遇皆美好~</li></ul><script>// 1.返回的是 获取过来元素对象的集合 以伪数组的形式存储的var lis = document.getElementsByTagName('li')console.log(lis);// 2.如果想要依次打印里面的元素对象我们可以采取遍历方式for (var i = 0; i < lis.length; i++) {console.log(lis[i]);}// 3.这里可以是可以获取标签的.getElementsByTagName()可以得到这个元素里面的某些标签var nav1 = document.getElementById('nav') //这个获取nav元素var navli = nav.getElementsByTagName('li') //这里是获取nav 里面的li标签 要先获取 nav元素在获取里面的liconsole.log(navli);</script></body> 3.通过 HTML5 新增的方法获取(注意兼容) 1. document.getElementsByClassName(‘类名’);// 根据类名返回元素对象集合 2. document.querySelector('选择器'); // 根据指定选择器返回第一个元素对象 3. document.querySelectorAll('选择器'); // 根据指定选择器返回所有元素对象集合 注意:querySelector 和 querySelectorAll里面的选择器需要加符号,比如:document.querySelector(’nav’); 代码演示 <body><div class="box">盒子1</div><div class="box">盒子2</div><div id="nav"><ul><li>首页</li><li>产品</li></ul></div><script>// 1. getElementsByClassName 根据类名获得某些元素集合var boxs = document.getElementsByClassName('box');console.log(boxs);// 2. querySelector 返回指定选择器的第一个元素对象 切记 里面的选择器需要加符号 .box navvar firstBox = document.querySelector('.box');console.log(firstBox);var nav = document.querySelector('nav');console.log(nav);var li = document.querySelector('li');console.log(li);// 3. querySelectorAll()返回指定选择器的所有元素对象集合var allBox = document.querySelectorAll('.box');console.log(allBox);var lis = document.querySelectorAll('li');console.log(lis);</script> 4.获取特殊元素(body,html) 获取body元素 - doucumnet.body // 返回body元素对象 获取html元素 . document.documentElement // 返回html元素对象 代码演示 <body><script>// 获取bdoy元素var bodyEle = document.bodyconsole.log(bodyEle); //返回body元素// 获取html元素var htmlEle = document.documentElementconsole.log(htmlEle); //返回html元素</script></body> 三.事件基础 1.事件概述 JavaScript 使我们有能力创建动态页面,而事件是可以被 JavaScript 侦测到的行为。 简单理解: 触发— 响应机制。 网页中的每个元素都可以产生某些可以触发 JavaScript 的事件,例如,我们可以在用户点击某按钮时产生一个 事件,然后去执行某些操作。 代码演示 <body><button id="btn">浩哥</button><script>// 点击一个按钮,弹出一个对话框// 1.事件是有三部分组成的 1.事件源 2.事件类型 3.事件处理程序 也称为事件三要素// (1).事件源 事件被触发的对象 var but = document.getElementById('btn')// (2).事件类型 如何触发 什么事件 比如鼠标点击(onclick) 还是鼠标经过还是????// (3).事件处理程序 通过一个函数赋值的方式 完成 因为函数就是实现某种功能的but.onclick = function() {alert('浩哥爱编程')}</script></body> 2.执行事件的步骤 1. 获取事件源DOM对象(意思是你要获取那个元素) 2. 注册事件(绑定事件 意思是通过什么方式来处理比如是鼠标经过还是鼠标点击等等行为) 3. 添加事件处理程序(采取函数赋值形式 意思是你想做啥) 代码演示 <body><div>123</div><script>// 事件执行步骤 点击div 控制台输出我被选中了// 1.获取事件源var div = document.querySelector('div')// 2.绑定事件 注册事件// div.onclick// 3.添加事件处理程序div.onclick = function() {console.log('我被点击了');}</script></body> 3.常见的鼠标事件 onmouseenter鼠标移入事件 onmouseleave鼠标移出事件 四.操作元素 JS的DOM操作可以改变网页内容、结构和样式,利用DOM操作元素来改变元素里面的内容、属性等。注意以下都是属性 1.操作元素内容(改变元素内容) elemeny.innerText 从起始位置到终止位置的内容,但它去除html标签,同时空格和换行也会去掉 elemernt.innerHTML 起始位置到终止位置的全部内容,包括html标签,同时保留空格和换行 elemernt.Content可以获取隐藏元素的文本,包含换行和空白 代码演示 <title>Document</title><style>div,p {height: 30px;width: 300px;line-height: 30px;text-align: center;color: fff;background-color: pink;}</style></head><body><button>显示当前系统时间</button><div>某个时间</div><p>123</p><script>// 当我们点击了按钮,div里面的文字会发生变化// 1.获取元素 注意这里的按钮 和div都要获取到 因为 点击按钮div里面要发生变化所以都要获取var but = document.querySelector('button');var div = document.querySelector('div');// 2.绑定事件// but.onclick// 3.程序处理but.onclick = function() {// 改变元素内容 element(元素).innerTextdiv.innerText = '2020-11-27'}// 4.我们元素可以不用添加事件,就可以直接显示日期var p = document.querySelector('p');p.innerText = '2020-11-27';</script> elemeny.innerText和elemeny.innerHTML的区别 代码演示 <body><div></div><p></p><ul><li> 文字</li><li>123</li></ul><script>// innertText 和 innertHTML 的区别// 1. innerText 不识别html标签 非标准 去除空格和换行var div = document.querySelector('div');div.innerText = '<strong>今天是:</strong> 2020';// 2.innertHTML 识别html标签 W3C标准 保留空格和换行的 推荐尽量使用这个 因为这个是标准var p = document.querySelector('p')p.innerHTML = '<strong>今天是:</strong> 2020';// 3.这俩个属性是可读写的 意思是 除了改变内容还可以元素读取里面的内容的var ul = document.querySelector('ul')console.log(ul.innerText);console.log(ul.innerHTML);// .4innerHtml innerText 之间的区别:设置内容的时候,如果内容当中包含标签字符串 innerHtml会有标签的特性,也就是说标签会在页面上生效如果内容当中包含标签字符串 innerText会把标签原样展示在页面上,不会让标签生效读取内容的时候,如果标签内部还有其它标签,innerHtml会把标签内部带着其它的标签全部输出如果标签内部还有其它标签,innerText只会输出所有标签里面的内容或者文本,不会输出标签如果标签内部没有其它标签,他们两个一致;都是读取文本内容,innerHtml会带空白和换行</script></body> 2. 操作常见元素属性 innerText、innerHTML 改变元素内容 src、href id、alt、title 代码演示 <body><button id="ldh">刘德华</button><button id="zxy">张学友</button><br><img src="./images/ldh.jpg" alt="" width="200px" height="200px" title="刘德华" id="img"><script>// 修改属性 src// 我们可以操作元素得方法 来修改元素得属性 就是 元素的是什么属性 在重新给值就可以完成相应的赋值操作了// 1.获取元素var ldh = document.getElementById('ldh')var zxy = document.getElementById('zxy')var img = document.getElementById('img')// 2.注册事件 程序处理zxy.onclick = function() {// 当我们点击了图片的时候图片路径就发生变化 这里的.表示 的 得意思 img对象下的src属性img.src = './images/zxy.jpg';// 当我们变换图片得同时里面得title也要跟着变 所以前面要加上img.img.title = '张学友';}ldh.onclick = function() {img.src = './images/ldh.jpg';img.title = '刘德华';}</script> 3.操作表单元素属性 利用DOM可以操作如下表单元素的属性 type、value、checked、selected、disabled 代码演示: <body><button>按钮</button><input type="text" value="输入内容"><script>// 我想把value里面的输入内容改变为 被点击了// 1.获取元素var but = document.querySelector('button')var input = document.querySelector('input')// 2.注册事件 处理程序but.onclick = function() {// input.innerHTML = '被点击了'; 这个是 普通盒子 比如 div 标签里面的内容// 表单里面的值 文字内容是通过value来修改的input.value = '被点击了'// 如果需要某个表单被禁用 不能再点击了使用 disabled 我们想要这个按钮 button禁用// but.disabled = true// 还有一种写法// this指向的是事件函数的调用者 谁调用就指向谁 这里调用者是btnthis.disabled = true}</script></body> 4.操作元素样式属性 我们可以通过 JS 修改元素的大小、颜色、位置等样式。 1.element.style 行内样式操作 注意: JS 里面的样式采取驼峰命名法 比如 fontSize、 backgroundColor JS 修改 style 样式操作,产生的是行内样式,所以行内式比内嵌式高 代码演示 <style>div {width: 200px;height: 200px;background-color: red;}</style></head><body><div></div><script>// 要求点击div变成粉色 height变为250px// 1.获取元素var div = document.querySelector('div');// 2.注册事件 处理程序div.onclick = function() {// div.style里面的属性 采取的是驼峰命名法// this等于div this调用者 谁调用谁执行this.style.backgroundColor = 'pink'this.style.height = '250px'}</script> 2.element.className 类名样式操作 注意: 如果样式修改较多,可以采取操作类名方式更改元素样式。 class因为是个保留字,因此使用className来操作元素类名属性 className 会直接更改元素的类名,会覆盖原先的类名。 代码演示 <style>div {width: 100px;height: 100px;background-color: pink;}.change {background-color: purple;color: fff;font-size: 25px;margin-top: 100px;}</style></head><body><div class="first">文本</div><script>// 1. 使用 element.style 获得修改元素样式 如果样式比较少 或者 功能简单的情况下使用var test = document.querySelector('div');test.onclick = function() {// this.style.backgroundColor = 'purple';// this.style.color = 'fff';// this.style.fontSize = '25px';// this.style.marginTop = '100px';// 让我们当前元素的类名改为了 change// 2. 我们可以通过 修改元素的className更改元素的样式 适合于样式较多或者功能复杂的情况 如果想继续添加样式即在change添加即可// 3. 如果想要保留原先的类名,我们可以这么做 多类名选择器// this.className = 'change';this.className = 'first change';}</script> 5.自定义属性的操作 js给我们规定了可以自己添加属性 在操作元素属性的时候,元素.语法只能操作元素天生具有的属性,如果是自定义的属性,通过.语法是无法操作的只能通过getAttribute和setAttribute去操作,他俩是通用的方法,无论元素天生的还是自定义的都可以可以操作 1.获取属性值 element.属性 获取属性值。 element.getAttribute(‘属性’); 区别: element.属性 获取内置属性值(元素本身自带的属性 如果是自定义属性不能被获取) element.getAttribute(‘属性’);主要获得自定义的属性 (标准) 我们自定义的属性 2.设置属性值 element.属性 = ‘值’ 设置内置属性值 element.setAttribute(‘属性’,‘值’) 区别: element.属性 设置内置属性值 element.setAttribute(‘属性’);主要设置自定义的属性(标准) 3.移除属性 element.removeAttribute(‘属性’); 代码演示 <body><div id="demo" index="1" class="nav"></div><script>var div = document.querySelector('div');// 1.获取元素的属性值// (1) element.属性console.log(div.id);// (2) element.getAttribute('属性') get获取得到 attribute属性的意思 我们自己添加的属性称之为自定义属性console.log(div.getAttribute('id')); //democonsole.log(div.getAttribute('index')); // 1// 2.设置元素的属性值// (1) element.属性 = '值' div.id = 'test'div.className = 'navs'// (2) element.setAttribute('属性','值')div.setAttribute('index', 2);div.setAttribute('class', 'footer') //这里就是class 不是className 比较特殊// 3.移除属性 removeAttribute(属性)div.removeAttribute('index');</script></body> 只要是自定义属性最好都是用element.setAttribute(‘属性’,‘值’)来设置 如果是自带属性用element.属性来设置 6.H5自定义属性 自定义属性的目的:第一、是为了保存属性 第二、并且使用数据。有一些数据可以保存到页面中而不用保存到数据库中。 自定义属性获取是通过getAttribute(‘属性’) 获取的 但是有些自定义属性很容易引起歧义,不容易判断是元素还是自定义属性 H5给我们新增了自定义属性: 1.设置H5自定义属性 H5规定自定义属性data-开头做为属性名并且赋值 比如<div data-index:“1”> 或者使用JS设置element.setAttribute(‘deta-index’,2) 2.获取H5自定义属性 兼容性获取 element.getAttribute(‘data-index’) 推荐开发中使用这个 H5新增element.dataset.index 或者element.datase[‘index’] ie 11以上才支持 代码演示 <body><div getTime="10" data-index="20" data-name-list="40"></div><script>// 获取元素var div = document.querySelector('div');console.log(div.geTime); //undefined getTime是自定义属性不能直接通过元素的属性来获取 而是用自定义属性来获取的getAttribute(‘属性’)console.log(div.getAttribute('getTime')); //10// H5添加自定义属性的写法以data-开头div.setAttribute('data-time', 30)// 1.兼容性获取H5自定义属性console.log(div.getAttribute('data-time')); // 30// 2.H5新增的获取自定义属性的方法 它只能获取data-开头的// dataset 是一个集合的意思存放了所有以data开头的自定义属性 如果你想取其中的某一个只需要在dataset.的后面加上自定义属性名即可console.log(div.dataset);console.log(div.dataset.time); // 30// 还有一种方法dataset['属性']console.log(div.dataset['time']); // 30// 如果自定义属性里面有多个-链接的单词 我们获取的时候采取驼峰命名法 不用要-了console.log(div.dataset.nameList); // 40console.log(div.dataset['nameList']); // 40</script></body> 五.节点操作 1.为什么要学习节点操作 获取元素通常使用俩种方式 (1)利用DOM提供的方法获取元素 但是逻辑性不强 繁琐 (2)利用节点层级关系获取元素 如 利用父子,兄弟关系获取元素 逻辑性强,但是兼容性不怎么好 2.节点概述 网页中的所有内容都是节点(标签、属性、文本、注释等等) ,在DOM中,节点使用node表示。HTML DOM 树中的所有节点均可通过javascript进行访问,所有HTML元素(节点) 均可被修改,也可以创建或删除 一般地,节点至少拥有nade Type(节点类型)、nodeName(节点名称)和nodeValue(节点值) 这三个基本属性 元素节点 nodeType 为 1 属性节点 node Name为 2 文本节点 nodeValue为 3 (文本节点包含文字、空格、换行等等) 实际开发中,节点操作主要操作的是元素节点 3.节点层级 利用DOM树可以把节点划分为不同得层级关系,常见得是父子兄层级关系 1.父级节点 1.node.parentNode parenNode属性可以返回某节点得父节点,注意是最近的父节点哟!!! 如果指定的节点没有父节点就返回null 代码演示 <body><div class="box"><div class="box1"></div></div><script>var box1 = document.querySelector('.box1')// 得到的是离元素最近的父节点(亲爸爸) 得不到就返回得是nullconsole.log(box1.parentNode); // parentNode 翻译过来就是父亲的节点</script></body> 2.子级节点操作 1.parentNode.children(非标准) parentNode.children 是一个只读属性,返回所有的子元素节点。它只返回子元素节点,其余节点不返回(重点记住这个就好,以后重点使用) 虽然children是一个非标准,但是得到了各个浏览器的支持,我们大胆使用即可!!! 代码演示 <body><ul><li>1</li><li>1</li><li>1</li><li>1</li></ul><script>// DOM 提供的方法(APL)获取 这样获取比较麻烦var ul = document.querySelector('ul')var lis = ul.querySelectorAll('li')// children子节点获取 ul里面所有的小li 放心使用没有限制兼容性 实际开发中经常使用的console.log(ul.children);</script> 如何返回子节点的第一个和最后一个? 2.parentNode.firstElementChild firstElementChild返回第一个子元素节点,找不到则返回unll 3.parentNode.lastElementChild lastElementChild返回最后一个子元素节点,找不到则返回null 注意:这俩个方法有兼容性问题,IE9以上才支持 谨慎使用 但是我们有解决方案 如果想要第一个子元素节点,可以使用 parentNode.chilren[0] 如果想要最后一个子元素节点,可以使用 parentNode.chilren[parentNode.chilren.length - 1] 代码演示 <body><ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul><script>var ul = document.querySelector('ul')// 1.firstElementChild 返回第一个子元素节点 ie9 以上才支持注意兼容console.log(ul.firstElementChild);// 2.lastElementChild返回最后一个子元素节点console.log(ul.lastElementChild);// 3.实际开发中用到的既没有兼容性问题又可以返回子节点的第一个和最后一个console.log(ul.children[0]);console.log(ul.children[ul.children.length - 1]); //ul.children.length - 1获取的永远是子节点最后一个</script></body> 3.兄弟节点 1.node.nextSibling nextSibling 返回当前元素的下一个兄弟节点,找不到则返回null。注意包含所有的节点 2.node.previousSibling previousSibling 返回当前元素上一个兄弟节点,找不到则返回null。注意包含所以有的节点 代码演示 <body><div>我是div</div><span>我是span</span><script>var div = document.querySelector('div')// 返回当前元素的下一个兄弟节点nextSibling,找不到返回null。注意包含元素节点或者文本节点等等console.log(div.nextSibling); //这里返回的是text 因为它的下一个兄弟节点是换行// 返回的是当前元素的上一个节点previousSibling,找不到返回null。注意包含元素节点或者文本节点等等console.log(div.previousSibling); //这里返回的是text 因为它的上一个兄弟节点是换行</script></body> 3.node.nexElementSibling nexElementSibling 返回当前元素下一个兄弟元素节点,找不到返回null 4.node.previousElementSibling previousElementSibling返回当前元素上一个兄弟节点,找不到返回null 注意:这俩个方法有兼容性问题,IE9以上才支持 代码演示 <body><div>我是div</div><span>我是span</span><script>var div = document.querySelector('div')// nextElementSiblingd得到下一个兄弟元素节点console.log(div.nextElementSibling); // span // previousElementSibling 得到的是上一个兄弟元素节点console.log(div.previousElementSibling); // null 因为它上面没有兄弟元素了返回空的</script></body> 怎么解决兼容性问题呢? 可以封装一个兼容性函数(简单了解即可 在实际开发中用的不多) function getNextElementSibling(element) {var el = element;while (el = el.nextSibling) {if (el.nodeType === 1) {return el;} }return null;} 4.创建节点 1.document.createElement('tagName') document.createElement( ) 方法创建由 tagName 指定的 HTML 元素。因为这些元素原先不存在的是根据我们的需求动态生成的,所有我们也称为动态创建元素节点 我们创建了节点要给添加到节点里面去 称为 添加节点 1.node.appendChild(child) node.appendChild( )方法将一个节点添加到指定父节点的子节点列表末尾 2.node.insertBefore(child,指定添加元素位置) node.insertBefore( ) 方法将一个节点添加到父节点的指定子节点前面 代码演示 <body><ul><li>1</li></ul><script>// 1.创建节点 createElementvar li = document.createElement('li')// 2.添加节点 创建了节点要添加到某一个元素身上去 叫添加节点 node.appendChild(child) done 父级 child 子级 如果前面有元素了则在后面追加元素类似数组中的push依次追加var ul = document.querySelector('ul')ul.appendChild(li)// 3.添加节点 node.insertBefore(child,指定元素) 在子节点前面添加子节点 child子级你要添加的元素var lili = document.createElement('li')ul.insertBefore(lili, ul.children[0]) //ul.children 这句话的意思是添加到ul父亲的子节点第一个// 总结 如果想在页面中添加元素分为俩步骤1.创建元素 2.添加元素</script></body> 5.删除节点 node.removeChild(child) node.removeChlid()方法从DOM 中删除一个子节点,返回删除的节点 简单点就是从父元素中删除某一个孩子node就是父亲child就是孩子 删除的节点.remove(没有参数) 注意:ie不支持 代码演示 <body><button>按钮</button><ul><li>熊大</li><li>熊二</li><li>熊三</li></ul><script>// 1.获取元素var ul = document.querySelector('ul')var but = document.querySelector('button');// 2.删除元素// but.onclick = function() {// ul.removeChild(ul.children[0])// }// 3.点击按钮键依次删除,最后没有删除内容了 就禁用按钮 disabled = true 禁用按钮语法but.onclick = function() {if (ul.children.length == 0) {this.disabled = true} else {ul.removeChild(ul.children[0])} }</script></body> 6.复制节点(克隆节点) node.cloneNode() node.dloneNode()方法返回调用该方法节点得一个副本,也称为克隆节点/拷贝节点 注意 1.如果括号参数为空或者为false,则是浅拷贝,只复制里面得标签,不复制内容 2.如果括号参数为true,则是深度拷贝,会复制节点本身以及里面所有的内容 代码演示 <body><ul><li>1</li><li>2</li><li>3</li></ul><script>// 1.获取元素var ul = document.querySelector('ul');// 2.复制元素 node.cloneNode() 如果参数括号为空或者false则只会复制元素不会复制内容,如果待有参数true则内容和元素都会被复制var lis = ul.children[0].cloneNode(true);// 3.获取元素ul.appendChild(lis)</script></body> 7.替换(改)节点 node.replaceChild(新节点,替换到什么位置) 代码演示 <body><ul class="list"><li>1</li><li>2</li></ul><script>// 替换(改)节点 父节点.replaceChild(新元素, 替换到什么位置)// (1)获取父元素var ulNode = document.querySelector('.list');// (2)创建新的元素var liRead = document.createElement('li')// (3)给新元素添加内容liRead.innerHTML = '5';// (4)替换元素ulNode.replaceChild(liRead, ulNode.children[1])</script></body> 8.三种动态创建元素区别 document.write() element.innerHTML document.createElement() 区别 document.write()是直接将内容写入页面的内容流,但是文档流执行完毕,它则会导致页面全部重绘 element.innerHTML是将内容写入某个DOM节点,不会导致页面全部重绘 element.innerHTML 创建多个元素效率更高(不要拼接字符串,采取数组形式拼接),结果有点复杂 createElement()创建多个元素效率低一点点,但是结果更加清晰 总结:不同浏览器下,innerHTML效率要比createElement()高 代码演示 <body><button>点击</button><p>abc</p><div class="inner"></div><div class="create"></div><script>// window.onload = function() {// document.write('<div>123</div>');// }// 三种创建元素方式区别 // 1. document.write() 创建元素 如果页面文档流加载完毕,再调用这句话会导致页面重绘// var btn = document.querySelector('button');// btn.onclick = function() {// document.write('<div>123</div>');// }// 2. innerHTML 创建元素var inner = document.querySelector('.inner');// for (var i = 0; i <= 100; i++) {// inner.innerHTML += '<a href="">百度</a>'// }var arr = [];for (var i = 0; i <= 100; i++) {arr.push('<a href="">百度</a>');}inner.innerHTML = arr.join('');// 3. document.createElement() 创建元素var create = document.querySelector('.create');for (var i = 0; i <= 100; i++) {var a = document.createElement('a');create.appendChild(a);}</script></body> 本篇文章为转载内容。原文链接:https://blog.csdn.net/m0_46978034/article/details/110190352。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-08-04 13:36:05
247
转载
转载文章
... onclick="node_create()"> 新增 </button><button class="btn btn-info" onclick="node_rename()"> 编辑</button><button class="btn btn-info" onclick="node_delete()"> 删除</button></div></div><div class="row" style="height: 5px;"></div><div class="row"> <div class="col-md-3"> <!-- 描述:搜索框 --> <div class="input-group row"> <span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-screenshot"></i></span> <input type="text" class="form-control" placeholder="请输入功能名称..." id="search_ay" aria-describedby="basic-addon1"> </div> <!--描述:jstree 树形菜单容器--> <div id="jstree_demo_div" class="row"> </div> </div> <div lass="col-md-9"> <button class="btn btn-tab" var='json/data.json'>data.json</button> <!--点击切换资源--> <button class="btn btn-tab" var='json/data2.json'>data2.json</button> <!--点击切换资源--> <button class="btn refresh "><i class="glyphicon glyphicon-refresh"></i></button> <!--点击刷新资源--> </div> </div> </div> <script src="jquery/jquery.min.js"></script><script src="jstree/dist/jstree.min.js"></script><script src="jstreeDemo.js?20180125"></script></body></html> 2.2、jstreeDemo.js代码 function jstree_fun(url){var $tree = $("jstree_demo_div").jstree({"core":{//'multiple': false, // 是否可以选择多个节点//"check_callback": true, // 允许拖动菜单 唯一 右键菜单"check_callback" : true,//设置为true,当用户修改数时,允许所有的交互和更好的控制(例如增删改)"themes" : { "stripes" : true },//主题配置对象,表示树背景是否有条带"data" : {//'url' : url,//'data' : function(node){//return { 'id' : node.id };//}"url" : url,"dataType" : "json"},"check_callback" : function(operation, node, node_parent, node_position, more){if(operation === "move_node"){var node = this.get_node(node_parent);if(node.id === ""){alert("根结点不可以删除");return false;}if(node.state.disabled){alert("禁用的不可以删除");return false;} }else if(operation === "delete_node"){var node = this.get_node(node_parent);if(node.id === ""){alert("根结点不可以删除");return false;} }return true;} },"plugins": [ //插件 "search", //允许插件搜索 // "sort", //排序插件 "state", //状态插件 "types", //类型插件 "unique", //唯一插件 "wholerow", //整行插件"contextmenu"],types:{ "default": { //设置默认的icon 图 "icon": "glyphicon glyphicon-folder-close", } } });$tree.on("open_node.jstree", function(e,data){ //监听打开事件var currentNode = data.node; data.instance.set_icon(currentNode, "glyphicon glyphicon-folder-open"); });$tree.on("close_node.jstree", function(e,data){ //监听关闭事件 var currentNode = data.node; data.instance.set_icon(currentNode, "glyphicon glyphicon-folder-close"); });$tree.on("activate_node.jstree", function(e, data){var currentNode = data.node; //获取当前节点的json .node //alert(currentNode.a_attr.id) //alert(currentNode.a_attr.href) //获取超链接的 .a_attr.href "链接" .a_attr.id ID //alert(currentNode.li_attr.href) //获取属性的 .li_attr.href "链接" .li_attr.id ID });// 创建$tree.on("create_node.jstree", function(e, data){alert("创建node节点");});// 修改$tree.on("rename_node.jstree", function(e, data){alert("修改node节点");});// 删除$tree.on("delete_node.jstree", function(e, data){alert("删除node节点");});// 查询节点名称var to = false;$("search_ay").keyup(function(){if(to){clearTimeout(to);}to = setTimeout(function(){$tree.jstree(true).search($('search_ay').val()); //开启插件查询后 使用这个方法可模糊查询节点 },250);});$('.btn-tab').click(function(){ //选项事件 //alert($(this).attr("var")) $tree.jstree(true).destroy(); //可做联级 $tree = jstree_fun($(this).attr("var"));//可做联级 //alert($(this).attr("var")) }); $('.refresh').click(function(){ //刷新事件 $tree.jstree(true).refresh () }); return $tree; }function node_create(){var ref = $("jstree_demo_div").jstree(true);var sel = ref.get_selected();if(!sel.length){alert("请先选择一个节点");return;}sel = sel[0];sel = ref.create_node(sel);if(sel){ref.edit(sel); } }function node_rename(){var ref = $("jstree_demo_div").jstree(true);var sel = ref.get_selected();if(!sel.length){alert("请先选择一个节点");return;}sel = sel[0];ref.edit(sel);}function node_delete(){var ref = $("jstree_demo_div").jstree(true);var sel = ref.get_selected();if(!sel.length){alert("请先选择一个节点");return;}sel = sel[0];if(ref.get_node(sel).parent==''){alert("根节点不允许删除");return;}ref.delete_node(sel);}// 初始化操作function init(){var $tree = jstree_fun("json/data.json");}init(); 3、图片效果展示 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_27717967/article/details/79167605。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-09-08 13:23:58
53
转载
Apache Atlas
...las是一个开源的大数据治理工具,可以帮助企业有效地管理他们的数据资产。嘿,伙计们,这篇东西会手把手地带你们探索Apache Atlas的四种最常见的部署方式,每种模式我都会配上鲜活的实例代码展示。这样一来,你们就能更直观、更接地气地理解和掌握Apache Atlas的使用诀窍啦! 二、单机部署模式 单机部署模式是最简单的部署方式,适合小规模的企业或团队使用。在单机部署模式下,所有组件都在同一台机器上运行。 1. 部署步骤 下载并解压Apache Atlas的安装包; 修改配置文件(如:conf/atlas-env.sh); 启动所有服务(如:bin/start-all.sh); 浏览器访问http://localhost:21000进行初始化设置。 以下是使用Apache Atlas创建一个项目的基本代码示例: javascript // 创建项目 POST http://localhost:21000/api/v2/project { "name": "my_project", "description": "My first project with Apache Atlas" } 三、集群部署模式 集群部署模式适合中大型企业或团队使用,可以提高系统的可用性和性能。 1. 部署步骤 在多台机器上安装并启动Apache Atlas的所有服务; 使用Zookeeper进行服务注册和发现; 使用Apache Atlas API进行项目管理和其他操作。 以下是使用Apache Atlas在集群中创建一个项目的代码示例: php-template // 获取Zookeeper集群的地址 GET http://localhost:2181/_clusterinfo // 创建项目 POST http://localhost:21000/api/v2/project { "name": "my_project", "description": "My first project with Apache Atlas" } 四、混合部署模式 混合部署模式结合了单机和集群的优势,既可以提供较高的性能,又可以保证数据的安全性和可靠性。 1. 部署步骤 在单台机器上安装并启动Apache Atlas的服务,作为中央控制节点; 在多台机器上安装并启动Apache Atlas的服务,作为数据处理节点; 使用Zookeeper进行服务注册和发现; 使用Apache Atlas API进行项目管理和其他操作。 以下是使用Apache Atlas在混合部署中创建一个项目的代码示例: javascript // 创建中央控制节点 GET http://localhost:21000/api/v2/projects // 获取Zookeeper集群的地址 GET http://localhost:2181/_clusterinfo // 创建数据处理节点 POST http://localhost:21000/api/v2/nodes { "hostName": "data-node-1", "port": 21001, "role": "DATA_NODE" } // 创建项目 POST http://localhost:21000/api/v2/project { "name": "my_project", "description": "My first project with Apache Atlas" } 五、微服务部署模式 微服务部署模式是近年来越来越流行的一种部署方式,可以让企业更加灵活地应对业务的变化和需求的增长。 1. 部署步骤 将Apache Atlas分解为多个微服务,例如:项目管理、数据目录、元数据存储等; 使用Docker进行容器化部署; 使用Kubernetes进行服务编排和管理; 使用Apache Atlas API进行项目管理和其他操作。 以下是使用Apache Atlas在微服务部署中创建一个项目的代码示例: javascript // 安装并启动项目管理微服务 docker run -d --name atlas-project-management my-atlas-project-management-image // 安装并启动数据目录微服务 docker run -d --name atlas-data-directory my-atlas-data-directory-image // 安装并启动元数据存储微服务 docker run -d --name atlas-metadata-storage my-atlas-metadata-storage-image // 创建项目 POST http://localhost:21000/api/v2/project { "name": "my_project", "description": "My first project with Apache Atlas" } 总结 Apache Atlas有多种部署模式供用户选择,用户可以根据自己的需求和技术条件来选择最合适的部署方式。甭管您选择哪种部署方式,Apache Atlas都能像个小助手一样,帮助企业老铁们把数据资产打理得井井有条,妥妥地保护好这些宝贝资源。
2023-07-31 15:33:19
456
月下独酌-t
ZooKeeper
...ZooKeeper在数据发布和订阅中的应用 1. 引言 在分布式系统中,数据的一致性和同步问题至关重要。ZooKeeper,这个家伙可厉害了,它就像是个超级靠谱的分布式协调员,在数据发布和订阅的舞台上,它的表现那叫一个光彩夺目。为啥呢?因为它有一套坚如磐石的数据一致性保障机制,让数据的同步和共享工作变得稳稳当当,棒极了!这篇文章将带你一起揭开ZooKeeper实现这个功能的秘密面纱,我们不仅会深入探讨其中的原理,还会通过一些实实在在的代码实例,手把手地带你体验这一功能的实际应用过程,让你仿佛身临其境。 1.1 ZooKeeper简介 ZooKeeper,这个名称听起来像是动物园管理员,但在IT世界中,它更像是一个维护分布式系统秩序的“管理员”。它提供了一个分布式的、开放源码的分布式应用程序协调服务,能够帮助开发人员解决分布式环境下的数据管理问题,如数据发布/订阅、命名服务、集群管理、分布式锁等。 2. 数据发布与订阅的挑战 在分布式环境中,数据发布与订阅面临的主要挑战是如何实时、高效、一致地将数据变更通知给所有订阅者。传统的解决方案可能会遭遇网络延迟、数据不一致等问题。而ZooKeeper借助其特有的数据模型(ZNode树)和Watcher机制,有效地解决了这些问题。 3. ZooKeeper在数据发布与订阅中的工作原理 3.1 ZNode和Watcher机制 ZooKeeper的数据模型采用的是类似于文件系统的树形结构——ZNode树。每个ZNode节点可以存储数据,并且可以注册Watcher监听器。当ZNode的数据有啥变动的时候,ZooKeeper这个小机灵鬼就会立马蹦跶起来,触发相应的Watcher事件,这样一来,咱们就能实时掌握到数据的最新动态啦。 3.2 数据发布流程 在数据发布过程中,发布者会在ZooKeeper上创建或更新特定的ZNode节点,节点的内容即为要发布的数据: java ZooKeeper zk = new ZooKeeper("localhost:2181", 5000, new Watcher() {...}); String data = "This is the published data"; zk.create("/publishPath", data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 3.3 数据订阅流程 订阅者则会在感兴趣的ZNode上设置Watcher监听器,一旦该节点的数据发生变化,订阅者就会收到通知并获取最新数据: java // 订阅者注册Watcher监听器 Stat stat = new Stat(); byte[] data = zk.getData("/publishPath", new Watcher() { @Override public void process(WatchedEvent event) { if (event.getType() == Event.EventType.NodeDataChanged) { // 当数据变化时,重新获取最新数据 byte[] newData = zk.getData("/publishPath", true, stat); System.out.println("Received new data: " + new String(newData)); } } }, stat); // 初始获取一次数据 System.out.println("Initial data: " + new String(data)); 4. 探讨与思考 ZooKeeper在数据发布与订阅中的应用,体现了其作为分布式协调服务的核心价值。它灵巧地借助了数据节点的变更事件触发机制,这样一来,发布数据的人就不用操心那些具体的订阅者都有谁,只需要在ZooKeeper上对数据节点进行操作,就能轻轻松松完成数据的发布。另一方面,订阅数据的朋友也不必像以前那样傻傻地不断轮询查看更新,他们可以聪明地“坐等”ZooKeeper发出的通知——Watcher事件,一旦这个事件触发,他们就能立刻获取到最新鲜、热乎的数据啦! 然而,这并不意味着ZooKeeper在数据发布订阅中是万能的。在面对大量用户同时在线这种热闹非凡的场景时,ZooKeeper这家伙有个小毛病,就是单个Watcher只能蹦跶一次,通知完就歇菜了。所以呢,为了让每一个关心消息更新的订阅者都不错过任何新鲜事儿,我们不得不绞尽脑汁设计一套更巧妙、更复杂的提醒机制。不管怎样,ZooKeeper可真是个大救星,实实在在地帮我们在复杂的分布式环境下搞定了数据同步这个难题,而且还带给我们不少灵活巧妙的解决思路。 总结来说,ZooKeeper在数据发布与订阅领域的应用,就像是一位经验丰富的乐队指挥,精确而有序地指引着每一位乐手,在分布式系统的交响乐章中奏出和谐的旋律。
2023-07-04 14:25:57
72
寂静森林
转载文章
...tice公司及其收购数据库技术公司–StormDB的产品。Postgres-XL是一个横向扩展的开源数据库集群,具有足够的灵活性来处理不同的数据库任务。 Postgres-XL功能特性 开放源代码:(源协议使用宽松的“Mozilla Public License”许可,允许将开源代码与闭源代码混在一起使用。) 完全的ACID支持 可横向扩展的关系型数据库(RDBMS) 支持OLAP应用,采用MPP(Massively Parallel Processing:大规模并行处理系统)架构模式 支持OLTP应用,读写性能可扩展 集群级别的ACID特性 多租户安全 也可被用作分布式Key-Value存储 事务处理与数据分析处理混合型数据库 支持丰富的SQL语句类型,比如:关联子查询 支持绝大部分PostgreSQL的SQL语句 分布式多版本并发控制(MVCC:Multi-version Concurrency Control) 支持JSON和XML格式 Postgres-XL缺少的功能 内建的高可用机制 使用外部机制实现高可能,如:Corosync/Pacemaker 有未来功能提升的空间 增加节点/重新分片数据(re-shard)的简便性 数据重分布(redistribution)期间会锁表 可采用预分片(pre-shard)方式解决,在同台物理服务器上建立多个数据节点,每个节点存储一个数据分片。数据重分布时,将一些数据节点迁出即可 某些外键、唯一性约束功能 Postgres-XL架构 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-M9lFuEIP-1640133702200)(./assets/postgre-xl.jpg)] 基于开源项目Postgres-XC XL增加了MPP,允许数据节点间直接通讯,交换复杂跨节点关联查询相关数据信息,减少协调器负载。 多个协调器(Coordinator) 应用程序的数据库连入点 分析查询语句,生成执行计划 多个数据节点(DataNode) 实际的数据存储 数据自动打散分布到集群中各数据节点 本地执行查询 一个查询在所有相关节点上并行查询 全局事务管理器(GTM:Global Transaction Manager) 提供事务间一致性视图 部署GTM Proxy实例,以提高性能 Postgre-XL主要组件 GTM (Global Transaction Manager) - 全局事务管理器 GTM是Postgres-XL的一个关键组件,用于提供一致的事务管理和元组可见性控制。 GTM Standby GTM的备节点,在pgxc,pgxl中,GTM控制所有的全局事务分配,如果出现问题,就会导致整个集群不可用,为了增加可用性,增加该备用节点。当GTM出现问题时,GTM Standby可以升级为GTM,保证集群正常工作。 GTM-Proxy GTM需要与所有的Coordinators通信,为了降低压力,可以在每个Coordinator机器上部署一个GTM-Proxy。 Coordinator --协调器 协调器是应用程序到数据库的接口。它的作用类似于传统的PostgreSQL后台进程,但是协调器不存储任何实际数据。实际数据由数据节点存储。协调器接收SQL语句,根据需要获取全局事务Id和全局快照,确定涉及哪些数据节点,并要求它们执行(部分)语句。当向数据节点发出语句时,它与GXID和全局快照相关联,以便多版本并发控制(MVCC)属性扩展到集群范围。 Datanode --数据节点 用于实际存储数据。表可以分布在各个数据节点之间,也可以复制到所有数据节点。数据节点没有整个数据库的全局视图,它只负责本地存储的数据。接下来,协调器将检查传入语句,并制定子计划。然后,根据需要将这些数据连同GXID和全局快照一起传输到涉及的每个数据节点。数据节点可以在不同的会话中接收来自各个协调器的请求。但是,由于每个事务都是惟一标识的,并且与一致的(全局)快照相关联,所以每个数据节点都可以在其事务和快照上下文中正确执行。 Postgres-XL继承了PostgreSQL Postgres-XL是PostgreSQL的扩展并继承了其很多特性: 复杂查询 外键 触发器 视图 事务 MVCC(多版本控制) 此外,类似于PostgreSQL,用户可以通过多种方式扩展Postgres-XL,例如添加新的 数据类型 函数 操作 聚合函数 索引类型 过程语言 安装 环境说明 由于资源有限,gtm一台、另外两台身兼数职。 主机名 IP 角色 端口 nodename 数据目录 gtm 192.168.20.132 GTM 6666 gtm /nodes/gtm 协调器 5432 coord1 /nodes/coordinator xl1 192.168.20.133 数据节点 5433 node1 /nodes/pgdata gtm代理 6666 gtmpoxy01 /nodes/gtm_pxy1 协调器 5432 coord2 /nodes/coordinator xl2 192.168.20.134 数据节点 5433 node2 /nodes/pgdata gtm代理 6666 gtmpoxy02 /nodes/gtm_pxy2 要求 GNU make版本 3.8及以上版本 [root@pg ~] make --versionGNU Make 3.82Built for x86_64-redhat-linux-gnuCopyright (C) 2010 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law. 需安装GCC包 需安装tar包 用于解压缩文件 默认需要GNU Readline library 其作用是可以让psql命令行记住执行过的命令,并且可以通过键盘上下键切换命令。但是可以通过--without-readline禁用这个特性,或者可以指定--withlibedit-preferred选项来使用libedit 默认使用zlib压缩库 可通过--without-zlib选项来禁用 配置hosts 所有主机上都配置 [root@xl2 11] cat /etc/hosts127.0.0.1 localhost192.168.20.132 gtm192.168.20.133 xl1192.168.20.134 xl2 关闭防火墙、Selinux 所有主机都执行 关闭防火墙: [root@gtm ~] systemctl stop firewalld.service[root@gtm ~] systemctl disable firewalld.service selinux设置: [root@gtm ~]vim /etc/selinux/config 设置SELINUX=disabled,保存退出。 This file controls the state of SELinux on the system. SELINUX= can take one of these three values: enforcing - SELinux security policy is enforced. permissive - SELinux prints warnings instead of enforcing. disabled - No SELinux policy is loaded.SELINUX=disabled SELINUXTYPE= can take one of three two values: targeted - Targeted processes are protected, minimum - Modification of targeted policy. Only selected processes are protected. mls - Multi Level Security protection. 安装依赖包 所有主机上都执行 yum install -y flex bison readline-devel zlib-devel openjade docbook-style-dsssl gcc 创建用户 所有主机上都执行 [root@gtm ~] useradd postgres[root@gtm ~] passwd postgres[root@gtm ~] su - postgres[root@gtm ~] mkdir ~/.ssh[root@gtm ~] chmod 700 ~/.ssh 配置SSH免密登录 仅仅在gtm节点配置如下操作: [root@gtm ~] su - postgres[postgres@gtm ~] ssh-keygen -t rsa[postgres@gtm ~] cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys[postgres@gtm ~] chmod 600 ~/.ssh/authorized_keys 将刚生成的认证文件拷贝到xl1到xl2中,使得gtm节点可以免密码登录xl1~xl2的任意一个节点: [postgres@gtm ~] scp ~/.ssh/authorized_keys postgres@xl1:~/.ssh/[postgres@gtm ~] scp ~/.ssh/authorized_keys postgres@xl2:~/.ssh/ 对所有提示都不要输入,直接enter下一步。直到最后,因为第一次要求输入目标机器的用户密码,输入即可。 下载源码 下载地址:https://www.postgres-xl.org/download/ [root@slave ~] ll postgres-xl-10r1.1.tar.gz-rw-r--r-- 1 root root 28121666 May 30 05:21 postgres-xl-10r1.1.tar.gz 编译、安装Postgres-XL 所有节点都安装,编译需要一点时间,最好同时进行编译。 [root@slave ~] tar xvf postgres-xl-10r1.1.tar.gz[root@slave ~] ./configure --prefix=/home/postgres/pgxl/[root@slave ~] make[root@slave ~] make install[root@slave ~] cd contrib/ --安装必要的工具,在gtm节点上安装即可[root@slave ~] make[root@slave ~] make install 配置环境变量 所有节点都要配置 进入postgres用户,修改其环境变量,开始编辑 [root@gtm ~]su - postgres[postgres@gtm ~]vi .bashrc --不是.bash_profile 在打开的文件末尾,新增如下变量配置: export PGHOME=/home/postgres/pgxlexport LD_LIBRARY_PATH=$PGHOME/lib:$LD_LIBRARY_PATHexport PATH=$PGHOME/bin:$PATH 按住esc,然后输入:wq!保存退出。输入以下命令对更改重启生效。 [postgres@gtm ~] source .bashrc --不是.bash_profile 输入以下语句,如果输出变量结果,代表生效 [postgres@gtm ~] echo $PGHOME 应该输出/home/postgres/pgxl代表生效 配置集群 生成pgxc_ctl.conf配置文件 [postgres@gtm ~] pgxc_ctl prepare/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxl/pgxc_ctl/pgxc_ctl_bash.ERROR: File "/home/postgres/pgxl/pgxc_ctl/pgxc_ctl.conf" not found or not a regular file. No such file or directoryInstalling pgxc_ctl_bash script as /home/postgres/pgxl/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxl/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxl/pgxc_ctl --configuration /home/postgres/pgxl/pgxc_ctl/pgxc_ctl.confFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxl/pgxc_ctl 配置pgxc_ctl.conf 新建/home/postgres/pgxc_ctl/pgxc_ctl.conf文件,编辑如下: 对着模板文件一个一个修改,否则会造成初始化过程出现各种神奇问题。 pgxcInstallDir=$PGHOMEpgxlDATA=$PGHOME/data pgxcOwner=postgres---- GTM Master -----------------------------------------gtmName=gtmgtmMasterServer=gtmgtmMasterPort=6666gtmMasterDir=$pgxlDATA/nodes/gtmgtmSlave=y Specify y if you configure GTM Slave. Otherwise, GTM slave will not be configured and all the following variables will be reset.gtmSlaveName=gtmSlavegtmSlaveServer=gtm value none means GTM slave is not available. Give none if you don't configure GTM Slave.gtmSlavePort=20001 Not used if you don't configure GTM slave.gtmSlaveDir=$pgxlDATA/nodes/gtmSlave Not used if you don't configure GTM slave.---- GTM-Proxy Master -------gtmProxyDir=$pgxlDATA/nodes/gtm_proxygtmProxy=y gtmProxyNames=(gtm_pxy1 gtm_pxy2) gtmProxyServers=(xl1 xl2) gtmProxyPorts=(6666 6666) gtmProxyDirs=($gtmProxyDir $gtmProxyDir) ---- Coordinators ---------coordMasterDir=$pgxlDATA/nodes/coordcoordNames=(coord1 coord2) coordPorts=(5432 5432) poolerPorts=(6667 6667) coordPgHbaEntries=(0.0.0.0/0)coordMasterServers=(xl1 xl2) coordMasterDirs=($coordMasterDir $coordMasterDir)coordMaxWALsernder=0 没设置备份节点,设置为0coordMaxWALSenders=($coordMaxWALsernder $coordMaxWALsernder) 数量保持和coordMasterServers一致coordSlave=n---- Datanodes ----------datanodeMasterDir=$pgxlDATA/nodes/dn_masterprimaryDatanode=xl1 主数据节点datanodeNames=(node1 node2)datanodePorts=(5433 5433) datanodePoolerPorts=(6668 6668) datanodePgHbaEntries=(0.0.0.0/0)datanodeMasterServers=(xl1 xl2)datanodeMasterDirs=($datanodeMasterDir $datanodeMasterDir)datanodeMaxWalSender=4datanodeMaxWALSenders=($datanodeMaxWalSender $datanodeMaxWalSender) 集群初始化,启动,停止 初始化 pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf init all 输出结果: /bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlStopping all the coordinator masters.Stopping coordinator master coord1.Stopping coordinator master coord2.pg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord1" does not existpg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord2" does not existDone.Stopping all the datanode masters.Stopping datanode master datanode1.Stopping datanode master datanode2.pg_ctl: PID file "/home/postgres/pgxc/nodes/datanode/datanode1/postmaster.pid" does not existIs server running?Done.Stop GTM masterwaiting for server to shut down.... doneserver stopped[postgres@gtm ~]$ echo $PGHOME/home/postgres/pgxl[postgres@gtm ~]$ ll /home/postgres/pgxl/pgxc/nodes/gtm/gtm.^C[postgres@gtm ~]$ pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf init all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlInitialize GTM masterERROR: target directory (/home/postgres/pgxc/nodes/gtm) exists and not empty. Skip GTM initilializationDone.Start GTM masterserver startingInitialize all the coordinator masters.Initialize coordinator master coord1.ERROR: target coordinator master coord1 is running now. Skip initilialization.Initialize coordinator master coord2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/coord/coord2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting coordinator master.Starting coordinator master coord1ERROR: target coordinator master coord1 is already running now. Skip initialization.Starting coordinator master coord22019-05-30 21:09:25.562 EDT [2148] LOG: listening on IPv4 address "0.0.0.0", port 54322019-05-30 21:09:25.562 EDT [2148] LOG: listening on IPv6 address "::", port 54322019-05-30 21:09:25.563 EDT [2148] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"2019-05-30 21:09:25.601 EDT [2149] LOG: database system was shut down at 2019-05-30 21:09:22 EDT2019-05-30 21:09:25.605 EDT [2148] LOG: database system is ready to accept connections2019-05-30 21:09:25.612 EDT [2156] LOG: cluster monitor startedDone.Initialize all the datanode masters.Initialize the datanode master datanode1.Initialize the datanode master datanode2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode1 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting all the datanode masters.Starting datanode master datanode1.WARNING: datanode master datanode1 is running now. Skipping.Starting datanode master datanode2.2019-05-30 21:09:33.352 EDT [2404] LOG: listening on IPv4 address "0.0.0.0", port 154322019-05-30 21:09:33.352 EDT [2404] LOG: listening on IPv6 address "::", port 154322019-05-30 21:09:33.355 EDT [2404] LOG: listening on Unix socket "/tmp/.s.PGSQL.15432"2019-05-30 21:09:33.392 EDT [2404] LOG: redirecting log output to logging collector process2019-05-30 21:09:33.392 EDT [2404] HINT: Future log output will appear in directory "pg_log".Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done.[postgres@gtm ~]$ pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf stop all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlStopping all the coordinator masters.Stopping coordinator master coord1.Stopping coordinator master coord2.pg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord1" does not existDone.Stopping all the datanode masters.Stopping datanode master datanode1.Stopping datanode master datanode2.pg_ctl: PID file "/home/postgres/pgxc/nodes/datanode/datanode1/postmaster.pid" does not existIs server running?Done.Stop GTM masterwaiting for server to shut down.... doneserver stopped[postgres@gtm ~]$ pgxc_ctl/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlPGXC monitor allNot running: gtm masterRunning: coordinator master coord1Not running: coordinator master coord2Running: datanode master datanode1Not running: datanode master datanode2PGXC stop coordinator master coord1Stopping coordinator master coord1.pg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord1" does not existDone.PGXC stop datanode master datanode1Stopping datanode master datanode1.pg_ctl: PID file "/home/postgres/pgxc/nodes/datanode/datanode1/postmaster.pid" does not existIs server running?Done.PGXC monitor allNot running: gtm masterRunning: coordinator master coord1Not running: coordinator master coord2Running: datanode master datanode1Not running: datanode master datanode2PGXC monitor allNot running: gtm masterNot running: coordinator master coord1Not running: coordinator master coord2Not running: datanode master datanode1Not running: datanode master datanode2PGXC exit[postgres@gtm ~]$ pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf init all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlInitialize GTM masterERROR: target directory (/home/postgres/pgxc/nodes/gtm) exists and not empty. Skip GTM initilializationDone.Start GTM masterserver startingInitialize all the coordinator masters.Initialize coordinator master coord1.Initialize coordinator master coord2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/coord/coord1 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/coord/coord2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting coordinator master.Starting coordinator master coord1Starting coordinator master coord22019-05-30 21:13:03.998 EDT [25137] LOG: listening on IPv4 address "0.0.0.0", port 54322019-05-30 21:13:03.998 EDT [25137] LOG: listening on IPv6 address "::", port 54322019-05-30 21:13:04.000 EDT [25137] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"2019-05-30 21:13:04.038 EDT [25138] LOG: database system was shut down at 2019-05-30 21:13:00 EDT2019-05-30 21:13:04.042 EDT [25137] LOG: database system is ready to accept connections2019-05-30 21:13:04.049 EDT [25145] LOG: cluster monitor started2019-05-30 21:13:04.020 EDT [2730] LOG: listening on IPv4 address "0.0.0.0", port 54322019-05-30 21:13:04.020 EDT [2730] LOG: listening on IPv6 address "::", port 54322019-05-30 21:13:04.021 EDT [2730] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"2019-05-30 21:13:04.057 EDT [2731] LOG: database system was shut down at 2019-05-30 21:13:00 EDT2019-05-30 21:13:04.061 EDT [2730] LOG: database system is ready to accept connections2019-05-30 21:13:04.062 EDT [2738] LOG: cluster monitor startedDone.Initialize all the datanode masters.Initialize the datanode master datanode1.Initialize the datanode master datanode2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode1 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting all the datanode masters.Starting datanode master datanode1.Starting datanode master datanode2.2019-05-30 21:13:12.077 EDT [25392] LOG: listening on IPv4 address "0.0.0.0", port 154322019-05-30 21:13:12.077 EDT [25392] LOG: listening on IPv6 address "::", port 154322019-05-30 21:13:12.079 EDT [25392] LOG: listening on Unix socket "/tmp/.s.PGSQL.15432"2019-05-30 21:13:12.114 EDT [25392] LOG: redirecting log output to logging collector process2019-05-30 21:13:12.114 EDT [25392] HINT: Future log output will appear in directory "pg_log".2019-05-30 21:13:12.079 EDT [2985] LOG: listening on IPv4 address "0.0.0.0", port 154322019-05-30 21:13:12.079 EDT [2985] LOG: listening on IPv6 address "::", port 154322019-05-30 21:13:12.081 EDT [2985] LOG: listening on Unix socket "/tmp/.s.PGSQL.15432"2019-05-30 21:13:12.117 EDT [2985] LOG: redirecting log output to logging collector process2019-05-30 21:13:12.117 EDT [2985] HINT: Future log output will appear in directory "pg_log".Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done. 启动 pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf start all 关闭 pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf stop all 查看集群状态 [postgres@gtm ~]$ pgxc_ctl monitor all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlRunning: gtm masterRunning: coordinator master coord1Running: coordinator master coord2Running: datanode master datanode1Running: datanode master datanode2 配置集群信息 分别在数据节点、协调器节点上分别执行以下命令: 注:本节点只执行修改操作即可(alert node),其他节点执行创建命令(create node)。因为本节点已经包含本节点的信息。 create node coord1 with (type=coordinator,host=xl1, port=5432);create node coord2 with (type=coordinator,host=xl2, port=5432);alter node coord1 with (type=coordinator,host=xl1, port=5432);alter node coord2 with (type=coordinator,host=xl2, port=5432);create node datanode1 with (type=datanode, host=xl1,port=15432,primary=true,PREFERRED);create node datanode2 with (type=datanode, host=xl2,port=15432);alter node datanode1 with (type=datanode, host=xl1,port=15432,primary=true,PREFERRED);alter node datanode2 with (type=datanode, host=xl2,port=15432);select pgxc_pool_reload(); 分别登陆数据节点、协调器节点验证 postgres= select from pgxc_node;node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id-----------+-----------+-----------+-----------+----------------+------------------+-------------coord1 | C | 5432 | xl1 | f | f | 1885696643coord2 | C | 5432 | xl2 | f | f | -1197102633datanode2 | D | 15432 | xl2 | f | f | -905831925datanode1 | D | 15432 | xl1 | t | f | 888802358(4 rows) 测试 插入数据 在数据节点1,执行相关操作。 通过协调器端口登录PG [postgres@xl1 ~]$ psql -p 5432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= create database lei;CREATE DATABASEpostgres= \c lei;You are now connected to database "lei" as user "postgres".lei= create table test1(id int,name text);CREATE TABLElei= insert into test1(id,name) select generate_series(1,8),'测试';INSERT 0 8lei= select from test1;id | name----+------1 | 测试2 | 测试5 | 测试6 | 测试8 | 测试3 | 测试4 | 测试7 | 测试(8 rows) 注:默认创建的表为分布式表,也就是每个数据节点值存储表的部分数据。关于表类型具体说明,下面有说明。 通过15432端口登录数据节点,查看数据 有5条数据 [postgres@xl1 ~]$ psql -p 15432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= \c lei;You are now connected to database "lei" as user "postgres".lei= select from test1;id | name----+------1 | 测试2 | 测试5 | 测试6 | 测试8 | 测试(5 rows) 登录到节点2,查看数据 有3条数据 [postgres@xl2 ~]$ psql -p15432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= \c lei;You are now connected to database "lei" as user "postgres".lei= select from test1;id | name----+------3 | 测试4 | 测试7 | 测试(3 rows) 两个节点的数据加起来整个8条,没有问题。 至此Postgre-XL集群搭建完成。 创建数据库、表时可能会出现以下错误: ERROR: Failed to get pooled connections 是因为pg_hba.conf配置不对,所有节点加上host all all 192.168.20.0/0 trust并重启集群即可。 ERROR: No Datanode defined in cluster 首先确认是否创建了数据节点,也就是create node相关的命令。如果创建了则执行select pgxc_pool_reload();使其生效即可。 集群管理与应用 表类型说明 REPLICATION表:各个datanode节点中,表的数据完全相同,也就是说,插入数据时,会分别在每个datanode节点插入相同数据。读数据时,只需要读任意一个datanode节点上的数据。 建表语法: CREATE TABLE repltab (col1 int, col2 int) DISTRIBUTE BY REPLICATION; DISTRIBUTE :会将插入的数据,按照拆分规则,分配到不同的datanode节点中存储,也就是sharding技术。每个datanode节点只保存了部分数据,通过coordinate节点可以查询完整的数据视图。 CREATE TABLE disttab(col1 int, col2 int, col3 text) DISTRIBUTE BY HASH(col1); 模拟数据插入 任意登录一个coordinate节点进行建表操作 [postgres@gtm ~]$ psql -h xl1 -p 5432 -U postgrespostgres= INSERT INTO disttab SELECT generate_series(1,100), generate_series(101, 200), 'foo';INSERT 0 100postgres= INSERT INTO repltab SELECT generate_series(1,100), generate_series(101, 200);INSERT 0 100 查看数据分布结果: DISTRIBUTE表分布结果 postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;xc_node_id | count ------------+-------1148549230 | 42-927910690 | 58(2 rows) REPLICATION表分布结果 postgres= SELECT count() FROM repltab;count -------100(1 row) 查看另一个datanode2中repltab表结果 [postgres@datanode2 pgxl9.5]$ psql -p 15432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= SELECT count() FROM repltab;count -------100(1 row) 结论:REPLICATION表中,datanode1,datanode2中表是全部数据,一模一样。而DISTRIBUTE表,数据散落近乎平均分配到了datanode1,datanode2节点中。 新增数据节点与数据重分布 在线新增节点、并重新分布数据。 新增datanode节点 在gtm集群管理节点上执行pgxc_ctl命令 [postgres@gtm ~]$ pgxc_ctl/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.confFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlPGXC 在服务器xl3上,新增一个master角色的datanode节点,名称是datanode3 端口号暂定5430,pool master暂定6669 ,指定好数据目录位置,从两个节点升级到3个节点,之后要写3个none none应该是datanodeSpecificExtraConfig或者datanodeSpecificExtraPgHba配置PGXC add datanode master datanode3 xl3 15432 6671 /home/postgres/pgxc/nodes/datanode/datanode3 none none none 等待新增完成后,查询集群节点状态: postgres= select from pgxc_node;node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id-----------+-----------+-----------+-----------+----------------+------------------+-------------datanode1 | D | 15432 | xl1 | t | f | 888802358datanode2 | D | 15432 | xl2 | f | f | -905831925datanode3 | D | 15432 | xl3 | f | f | -705831925coord1 | C | 5432 | xl1 | f | f | 1885696643coord2 | C | 5432 | xl2 | f | f | -1197102633(4 rows) 节点新增完毕 数据重新分布 由于新增节点后无法自动完成数据重新分布,需要手动操作。 DISTRIBUTE表分布在了node1,node2节点上,如下: postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;xc_node_id | count ------------+-------1148549230 | 42-927910690 | 58(2 rows) 新增一个节点后,将sharding表数据重新分配到三个节点上,将repl表复制到新节点 重分布sharding表postgres= ALTER TABLE disttab ADD NODE (datanode3);ALTER TABLE 复制数据到新节点postgres= ALTER TABLE repltab ADD NODE (datanode3);ALTER TABLE 查看新的数据分布: postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;xc_node_id | count ------------+--------700122826 | 36-927910690 | 321148549230 | 32(3 rows) 登录datanode3(新增的时候,放在了xl3服务器上,端口15432)节点查看数据: [postgres@gtm ~]$ psql -h xl3 -p 15432 -U postgrespsql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= select count() from repltab;count -------100(1 row) 很明显,通过 ALTER TABLE tt ADD NODE (dn)命令,可以将DISTRIBUTE表数据重新分布到新节点,重分布过程中会中断所有事务。可以将REPLICATION表数据复制到新节点。 从datanode节点中回收数据 postgres= ALTER TABLE disttab DELETE NODE (datanode3);ALTER TABLEpostgres= ALTER TABLE repltab DELETE NODE (datanode3);ALTER TABLE 删除数据节点 Postgresql-XL并没有检查将被删除的datanode节点是否有replicated/distributed表的数据,为了数据安全,在删除之前需要检查下被删除节点上的数据,有数据的话,要回收掉分配到其他节点,然后才能安全删除。删除数据节点分为四步骤: 1.查询要删除节点dn3的oid postgres= SELECT oid, FROM pgxc_node;oid | node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id -------+-----------+-----------+-----------+-----------+----------------+------------------+-------------11819 | coord1 | C | 5432 | datanode1 | f | f | 188569664316384 | coord2 | C | 5432 | datanode2 | f | f | -119710263316385 | node1 | D | 5433 | datanode1 | f | t | 114854923016386 | node2 | D | 5433 | datanode2 | f | f | -92791069016397 | dn3 | D | 5430 | datanode1 | f | f | -700122826(5 rows) 2.查询dn3对应的oid中是否有数据 testdb= SELECT FROM pgxc_class WHERE nodeoids::integer[] @> ARRAY[16397];pcrelid | pclocatortype | pcattnum | pchashalgorithm | pchashbuckets | nodeoids ---------+---------------+----------+-----------------+---------------+-------------------16388 | H | 1 | 1 | 4096 | 16397 16385 1638616394 | R | 0 | 0 | 0 | 16397 16385 16386(2 rows) 3.有数据的先回收数据 postgres= ALTER TABLE disttab DELETE NODE (dn3);ALTER TABLEpostgres= ALTER TABLE repltab DELETE NODE (dn3);ALTER TABLEpostgres= SELECT FROM pgxc_class WHERE nodeoids::integer[] @> ARRAY[16397];pcrelid | pclocatortype | pcattnum | pchashalgorithm | pchashbuckets | nodeoids ---------+---------------+----------+-----------------+---------------+----------(0 rows) 4.安全删除dn3 PGXC$ remove datanode master dn3 clean 故障节点FAILOVER 1.查看当前集群状态 [postgres@gtm ~]$ psql -h xl1 -p 5432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= SELECT oid, FROM pgxc_node;oid | node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id-------+-----------+-----------+-----------+-----------+----------------+------------------+-------------11739 | coord1 | C | 5432 | xl1 | f | f | 188569664316384 | coord2 | C | 5432 | xl2 | f | f | -119710263316387 | datanode2 | D | 15432 | xl2 | f | f | -90583192516388 | datanode1 | D | 15432 | xl1 | t | t | 888802358(4 rows) 2.模拟datanode1节点故障 直接关闭即可 PGXC stop -m immediate datanode master datanode1Stopping datanode master datanode1.Done. 3.测试查询 只要查询涉及到datanode1上的数据,那么该查询就会报错 postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;WARNING: failed to receive file descriptors for connectionsERROR: Failed to get pooled connectionsHINT: This may happen because one or more nodes are currently unreachable, either because of node or network failure.Its also possible that the target node may have hit the connection limit or the pooler is configured with low connections.Please check if all nodes are running fine and also review max_connections and max_pool_size configuration parameterspostgres= SELECT xc_node_id, FROM disttab WHERE col1 = 3;xc_node_id | col1 | col2 | col3------------+------+------+-------905831925 | 3 | 103 | foo(1 row) 测试发现,查询范围如果涉及到故障的node1节点,会报错,而查询的数据范围不在node1上的话,仍然可以查询。 4.手动切换 要想切换,必须要提前配置slave节点。 PGXC$ failover datanode node1 切换完成后,查询集群 postgres= SELECT oid, FROM pgxc_node;oid | node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id -------+-----------+-----------+-----------+-----------+----------------+------------------+-------------11819 | coord1 | C | 5432 | datanode1 | f | f | 188569664316384 | coord2 | C | 5432 | datanode2 | f | f | -119710263316386 | node2 | D | 15432 | datanode2 | f | f | -92791069016385 | node1 | D | 15433 | datanode2 | f | t | 1148549230(4 rows) 发现datanode1节点的ip和端口都已经替换为配置的slave了。 本篇文章为转载内容。原文链接:https://blog.csdn.net/qianglei6077/article/details/94379331。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-30 11:09:03
94
转载
JSON
...SON 是一种简洁的数据交换格式,它普遍用在前后端数据传输。而 jQuery 是一款流行的 JavaScript 库,常用于操作 DOM、发起 AJAX 请求以及处理 JSON 数据的操作。 在 jQuery 中,我们可以通过几个函数来完成对 JSON 数据的查询操作。 // 一个基础的 JSON 数据例子 var data = { "name": "小明", "age": 18, "hometown": "北京", "hobbies": ["吃饭", "睡觉", "打游戏"], "friend": { "name": "小红", "age": 17 } } 1. $.parseJSON() var jsonStr = '{"name":"小明","age":18,"hometown":"北京"}'; var jsonData = $.parseJSON(jsonStr); console.log(jsonData.name); // 显示:小明 2. $.getJSON() $.getJSON('https://api.github.com/users/octocat', function(data) { console.log(data.name); // 显示:The Octocat }); 3. $.each() $.each(data.hobbies, function(index, value) { console.log(value); // 显示:吃饭、睡觉、打游戏 }); 4. $.map() var hobbiesArr = $.map(data.hobbies, function(value, index) { return value; }); console.log(hobbiesArr); // 显示:["吃饭", "睡觉", "打游戏"] 以上就是 jQuery 中常用的几种 JSON 查询函数,它们可以使我们更便捷地对数据进行操作。
2023-07-24 23:16:09
441
逻辑鬼才
ReactJS
...上。 三、树形数据结构 在实际的应用中,我们通常会遇到树形的数据结构,如菜单、目录等。在这种情况下,咱们完全可以利用React的那个render方法,再加上递归这个小技巧,来一步步“爬”遍整个组件树。然后呢,针对每个节点的不同状态和属性,咱们就可以灵活地、动态地生成对应的DOM元素啦,就像变魔术一样! jsx // A component that represents a tree node. function TreeNode({ label, children }) { return ( {label} {children && ( {children.map(child => ( ))} )} ); } // A function that generates a tree from an array of nodes. function generateTree(nodes) { return nodes.reduce((acc, node) => { acc[node.id] = { ...node, children: generateTree(node.children || []) }; return acc; }, {}); } // An example tree with three levels. const treeData = generateTree([ { id: 1, label: "Root", children: [ { id: 2, label: "Level 1", children: [ { id: 3, label: "Level 2", children: [{ id: 4, label: "Leaf" }], }, ], }, ], }, ]); // Render the tree using recursion. function renderTree(treeData) { return Object.keys(treeData).map(id => { const node = treeData[id]; return ( key={id} label={node.label} children={node.children && renderTree(node.children)} /> ); }); } ReactDOM.render( {renderTree(treeData)} , document.getElementById("root")); 在上面的例子中,TreeNode组件表示树的一个节点,generateTree函数用于生成树的结构,renderTree函数则使用递归的方式遍历整个树,并根据每个节点的状态和属性动态生成DOM元素。 以上就是我在使用ReactJS过程中的一些心得和体会。希望这些内容能对你有所帮助。
2023-05-09 23:53:32
152
断桥残雪-t
Etcd
...运行时的基本信息,如节点启动、客户端连接等。 - Warning:记录潜在错误或非预期行为,但不影响程序正常运行。 - Error:记录已发生错误,可能影响部分功能。 - Fatal:记录严重错误,导致进程终止。 2. 设置Etcd日志级别 Etcd的日志级别可以通过启动参数--log-level来设定。下面是一段启动Etcd并将其日志级别设置为info的示例代码: bash ./etcd --name my-etcd-node \ --data-dir /var/lib/etcd \ --listen-peer-urls http://localhost:2380 \ --listen-client-urls http://localhost:2379 \ --initial-cluster-token etcd-cluster-1 \ --initial-cluster=my-etcd-node=http://localhost:2380 \ --advertise-client-urls http://localhost:2379 \ --log-level=info 上述命令行中--log-level=info表示我们只关心Info及以上级别的日志信息。 3. 输出方式与格式化 Etcd默认将日志输出到标准错误(stderr),你也可以通过--log-output参数指定输出文件,例如: bash ./etcd --log-output=/var/log/etcd.log ... 此外,Etcd还支持JSON格式的日志输出,只需添加启动参数--log-format=json即可: bash ./etcd --log-format=json ... 4. 实践应用与思考 在日常运维过程中,我们可能会遇到各种场景需要调整Etcd的日志级别。比如,当我们的集群闹脾气、出现状况时,我们可以临时把日志的“放大镜”调到Debug级别,这样就能捞到更多更细枝末节的内部运行情况,像侦探一样迅速找到问题的幕后黑手。而在平时一切正常运转的日子里,为了让日志系统保持高效、易读,我们一般会把它调到Info或者Warning这个档位,就像给系统的日常表现打个合适的标签。 同时,合理地选择日志输出方式也很重要。直接输出至终端有利于实时监控,但不利于长期保存和分析。所以,在实际的生产环境里,我们通常会选择把日志稳稳地存到磁盘上,这样一来,以后想回过头来找找线索、分析问题什么的,就方便多了。 总的来说,熟练掌握Etcd日志级别的调整和输出方式,不仅能让我们更好地理解Etcd的工作状态,更能提升我们对分布式系统管理和运维的实战能力。这就像一位超级厉害的侦探大哥,他像拿着放大镜一样细致地研究Etcd日志,像读解神秘密码那样解读其中的含义。通过这种抽丝剥茧的方式,他成功揭开了集群背后那些不为人知的小秘密,确保我们的系统能够稳稳当当地运行起来。
2023-01-29 13:46:01
832
人生如戏
ZooKeeper
...oKeeper的临时节点这个功能时,可能会碰到一个叫"NoChildrenForEphemeralException"的小插曲。这个异常呢,大多数情况下,都是在你想给临时节点添个“小崽崽”(创建子节点)的时候蹦出来的。本文将通过深入探讨该异常的含义、产生原因,并结合实际代码示例,来分享如何有效地处理这一问题。 一、理解NoChildrenForEphemeralException(2) NoChildrenForEphemeralException是ZooKeeper客户端API抛出的一种异常类型,它明确地告诉我们一个核心原则:在ZooKeeper中,临时节点不允许拥有子节点。这是因为临时节点的存在时间是紧跟它创建者的“脚步”的,就像会话结束就等于游戏over一样。只要这个会话说“拜拜”,那个临时节点连同它的小弟——所有相关数据,都会被系统自动毫不留情地清理掉。因此,允许临时节点有子节点将会导致数据不一致性和清理困难的问题。 二、异常产生的场景分析(3) 想象一下这样的场景:我们的应用正在使用ZooKeeper进行服务注册,其中每个服务实例都以临时节点的形式存在。如果咱想在某个服务的小实例(也就是临时节点)下面整出个子节点,用来表示这个服务更多的信息,这时候可能会蹦出来一个“NoChildrenForEphemeralException”的错误提示。 java String servicePath = "/services/serviceA"; String instancePath = zk.create(servicePath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); // 尝试在临时节点下创建子节点 String subNodePath = zk.create(instancePath + "/subnode", "additionalInfo".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 上述代码段在执行zk.create()操作时,如果instancePath是一个临时节点,那么就会抛出"NoChildrenForEphemeralException"异常。 三、处理NoChildrenForEphemeralException的方法(4) 面对这个问题,我们需要重新设计数据模型,避免在临时节点下创建子节点。一个我们常会用到的办法就是在注册服务的时候,别把服务实例的相关信息设置成子节点,而是直接把它塞进临时节点的数据内容里头。就像是你往一个临时的文件夹里放信息,而不是另外再创建一个小文件夹来装它,这样更直接、更方便。 java String servicePath = "/services/serviceA"; byte[] data = "additionalInfo".getBytes(); String instancePath = zk.create(servicePath + "/instance_", data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); 在这个例子中,我们将附加信息直接写入临时节点的数据部分,这样既满足了数据存储的需求,又遵循了ZooKeeper关于临时节点的约束规则。 四、思考与讨论(5) 处理"NoChildrenForEphemeralException"的关键在于理解和尊重ZooKeeper对临时节点的设定。这种表面上看着像是在“画地为牢”的设计,其实背后藏着一个大招,就是为了确保咱们分布式系统里的数据能够保持高度的一致性和安全性。在实际动手操作时,我们不光得把ZooKeeper API玩得贼溜,更要像侦探破案那样,抽丝剥茧地理解它背后的运行机制。这样一来,咱们才能在实际项目中把它运用得更加得心应手,解决那些可能冒出来的各种疑难杂症。 总结起来,当我们在使用ZooKeeper构建分布式系统时,对于"NoChildrenForEphemeralException"这类异常,我们应该积极地调整策略,遵循其设计规范,而非试图绕过它。只有这样,才能让ZooKeeper充分发挥其协调作用,服务于我们的分布式架构。这个过程,其实就跟咱们人类遇到挑战时的做法一样,不断反刍琢磨、摸索探寻、灵活适应,满载着各种主观情感的火花和智慧碰撞的精彩瞬间,简直不要太有魅力啊!
2023-07-29 12:32:47
65
寂静森林
ZooKeeper
...在操作一样,新建一个节点、读取存储的信息,或者是同步执行一些操作这类工作,它们完成的平均耗时,可是衡量ZooKeeper表现优不优秀的关键指标之一。理解并优化这些延迟有助于提升整体系统的响应速度。 java // 示例代码:使用ZooKeeper客户端创建节点并测量耗时 long startTime = System.nanoTime(); zooKeeper.create("/testNode", "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); long endTime = System.nanoTime(); double elapsedTimeMs = (endTime - startTime) / 1e6; System.out.println("Time taken to create node: " + elapsedTimeMs + " ms"); 2. 吞吐量 ZooKeeper每秒处理的事务数量(TPS)也是衡量其性能的关键指标。这包括但不限于,比如新建一个节点、给已有数据来个更新这类写入操作,也涵盖了读取信息内容,还有维持和管理会话这些日常必备操作。 3. 并发连接数 ZooKeeper能够同时处理的客户端连接数对其性能有直接影响。过高的并发连接可能会导致资源瓶颈,从而影响服务质量和稳定性。 4. 节点数量与数据大小 随着ZooKeeper中存储的数据节点数量增多或者单个节点的数据量增大,其性能可能会下降,因此对这些数据规模的增长需要持续关注。 三、ZooKeeper监控工具及其应用 1. ZooInspector 这是一个图形化的ZooKeeper浏览器,可以帮助我们直观地查看ZooKeeper节点结构、数据内容以及节点属性,便于我们实时监控ZooKeeper的状态和变化。 2. ZooKeeper Metrics ZooKeeper内置了一套丰富的度量指标,通过JMX(Java Management Extensions)可以导出这些指标,然后利用Prometheus、Grafana等工具进行可视化展示和报警设置。 xml ... tickTime 2000 admin.enableServer true jmxPort 9999 ... 3. Zookeeper Visualizer 这款工具能将ZooKeeper的节点关系以图形化的方式展现出来,有助于我们理解ZooKeeper内部数据结构的变化情况,对于性能分析和问题排查非常有用。 四、结语 理解并有效监控ZooKeeper的各项性能指标,就像是给分布式系统的心脏装上了心电图监测仪,让运维人员能实时洞察到系统运行的健康状况。在实际操作的时候,咱们得瞅准业务的具体情况,灵活地调整ZooKeeper的配置设定。这就像是在调校赛车一样,得根据赛道的不同特点来微调车辆的各项参数。同时呢,咱们还要手握这些监控工具,持续给咱们的ZooKeeper集群“动手术”,让它性能越来越强劲。这样一来,才能确保咱们的分布式系统能够跑得飞快又稳当,始终保持高效、稳定的运作状态。这个过程就像一场刺激的探险之旅,充满了各种意想不到的挑战和尝试。不过,也正是因为这份对每一个细节都精雕细琢、追求卓越的精神,才让我们的技术世界变得如此五彩斑斓,充满无限可能与惊喜。
2023-05-20 18:39:53
441
山涧溪流
Element-UI
...,特别是在处理复杂的数据结构时,可能会出现一些意想不到的问题。今天,咱们就来唠唠一个大家可能常遇到的小麻烦:在使用Element-UI的树形组件时,突然发现节点渲染出了岔子,要么是无法顺利展开查看具体内容,要么就是收起功能罢工了。 二、问题背景 首先,我们需要了解一下什么是树形控件。树形控件是一种展示数据结构为树状的数据视图组件。在Element-UI中,它是一个非常实用的组件,可以帮助我们在网页上清晰地呈现复杂的层次结构数据。 然而,在实际应用中,我们可能遇到这样的情况:在使用Element-UI的树形控件时,部分节点无法正常展开或收起,或者出现渲染错误。这可能是由于我们的代码捣鼓得不够到位,或者说是Element-UI自身的一些小限制在背后搞鬼导致的。 三、原因分析 那么,为什么会出现这种问题呢?我们可以从以下几个方面进行分析: 1. 数据源问题 首先,我们需要检查一下我们的数据源是否正确。如果数据源存在错误,那么很可能会影响到树形控件的正常显示。 2. 展开或收起逻辑问题 其次,我们也需要检查一下我们的展开或收起逻辑是否正确。比如,想象一下这种情况,就像一棵大树,我们得先确保所有的枝干(也就是父节点)都已经被妥妥地展开啦,然后才能顺利地把那些小树枝(子节点)也一一打开。 3. Element-UI版本问题 最后,我们还需要考虑一下Element-UI的版本问题。不同版本的Element-UI可能存在一些兼容性问题,也可能有一些新的特性和API。 四、解决方案 知道了问题的原因之后,接下来就是寻找解决方案了。下面是一些可能的解决方案: 1. 检查数据源 首先,我们需要仔细检查一下我们的数据源是否正确。如果有任何错误,我们都需要及时修复。 2. 优化展开或收起逻辑 其次,我们也可以尝试优化我们的展开或收起逻辑。比如,我们可以在程序里加一个计数器,就像查户口似的,来确保每一个“爸爸节点”都乖乖地、准确无误地展开了。 3. 更新Element-UI版本 如果以上方法都无法解决问题,那么我们还可以尝试更新Element-UI的版本。新版本的Element-UI可能已经修复了一些旧版本存在的问题。 五、代码示例 为了更好地理解和解决这个问题,下面我们通过一个简单的例子来进行演示。 html :data="treeData" node-key="id" show-checkbox default-expand-all expand-on-click-node highlight-current @node-click="handleNodeClick" > 在这个例子中,我们定义了一个树形控件,并传入了一组数据作为数据源。然后呢,我们给node-click事件装上了“监听器”,就像派了个小侦探守在那儿。当用户心血来潮点到某个节点时,这位小侦探就立马行动,把那个被点中的节点信息给咱详细报告出来。 如果在运行这段代码时,你发现某些节点无法正常展开或收起,那么你就需要根据上述的方法来进行排查和解决。 六、结语 总的来说,使用Element-UI的树形控件时节点渲染错误或无法展开与收起,这可能是因为我们的代码实现存在问题,或者是Element-UI本身的一些限制导致的。但是,只要我们能像侦探一样,准确找到问题藏身之处,然后对症下药,采取合适的解决策略,那么这个问题肯定能被我们手到擒来,顺利解决掉。所以,让我们一起努力,让前端开发变得更简单、更高效吧!
2023-08-31 16:39:17
504
追梦人-t
ZooKeeper
...eper中设置和获取节点的数据? 1. 简介 嗨,大家好!今天我们要聊的是Apache ZooKeeper,这是一款超级实用且功能强大的分布式协调服务。这个工具能帮我们搞定集群里头的各种复杂活儿,比如设置管理、名字服务,还有分布式锁这些 tricky 的事情。而今天我们主要讨论的是如何在ZooKeeper中设置和获取节点的数据。这个过程虽然看起来简单,但其中却蕴含了不少技巧和经验。废话不多说,让我们直接进入正题吧! 2. 安装与配置 首先,我们需要确保ZooKeeper已经正确安装并运行。如果你是新手,不妨先看看官方文档,学着自己安装一下。或者,你也可以直接用Docker,几下敲敲代码就搞定了,超级方便! bash docker run -d --name zookeeper -p 2181:2181 zookeeper 这样我们就有了一个本地的ZooKeeper服务。接下来,我们可以开始编写客户端代码了。 3. 设置数据 3.1 使用Java API设置数据 让我们先从Java API开始。想象一下,我们要在系统里建个新家,就叫它/myapp/config吧。然后呢,我们往这个新家里放点儿配置文件,好让它知道该怎么干活。下面是一个简单的代码示例: java import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs.Ids; public class ZookeeperExample { public static void main(String[] args) throws Exception { // 创建ZooKeeper实例 ZooKeeper zk = new ZooKeeper("localhost:2181", 5000, watchedEvent -> {}); // 设置节点数据 byte[] data = "some config data".getBytes(); String path = "/myapp/config"; // 创建临时节点 String createdPath = zk.create(path, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); System.out.println("Created node: " + createdPath); // 关闭连接 zk.close(); } } 在这个例子中,我们首先创建了一个ZooKeeper实例,并指定了连接超时时间。然后呢,我们就用create这个魔法命令变出了一个持久节点,还往里面塞了一些配置信息。最后,我们关闭了连接。 3.2 使用Python API设置数据 如果你更喜欢Python,也可以使用Python客户端库kazoo来操作ZooKeeper。下面是一个简单的示例: python from kazoo.client import KazooClient zk = KazooClient(hosts='127.0.0.1:2181') zk.start() 设置节点数据 zk.create('/myapp/config', b'some config data', makepath=True) print("Node created") zk.stop() 这段代码同样创建了一个持久节点,并写入了一些配置信息。这里我们使用了makepath=True参数来自动创建父节点。 4. 获取数据 4.1 使用Java API获取数据 接下来,我们来看看如何获取节点的数据。假设我们要读取刚刚创建的那个节点中的配置信息,可以这样做: java import org.apache.zookeeper.ZooKeeper; public class ZookeeperExample { public static void main(String[] args) throws Exception { // 创建ZooKeeper实例 ZooKeeper zk = new ZooKeeper("localhost:2181", 5000, watchedEvent -> {}); // 获取节点数据 byte[] data = zk.getData("/myapp/config", false, null); System.out.println("Data: " + new String(data)); // 关闭连接 zk.close(); } } 在这个例子中,我们使用getData方法读取了节点/myapp/config中的数据,并将其转换为字符串打印出来。 4.2 使用Python API获取数据 同样地,使用Python的kazoo库也可以轻松完成这一操作: python from kazoo.client import KazooClient zk = KazooClient(hosts='127.0.0.1:2181') zk.start() 获取节点数据 data, stat = zk.get('/myapp/config') print("Node data: " + data.decode()) zk.stop() 这里我们使用了get方法来获取节点数据,同时返回了节点的状态信息。 5. 总结与思考 通过上面的代码示例,我们可以看到,无论是使用Java还是Python,设置和获取ZooKeeper节点数据的过程都非常直观。但实际上,在真实使用中可能会碰到一些麻烦,比如说网络卡顿啊,或者有些节点突然不见了之类的。这就得在开发时不断地调整和改进,确保系统又稳又靠谱。 希望今天的分享对你有所帮助!如果你有任何问题或建议,欢迎随时交流。
2025-01-25 15:58:48
45
桃李春风一杯酒
MemCache
...多个MemCache节点,实现数据的分布式存储和同步更新? 随着互联网业务规模的不断扩大,MemCache作为一种高效的分布式缓存系统,在处理高并发、大数据量场景中发挥着重要作用。不过,在实际动手布阵这套系统的时候,如何在满是分散节点的环境里头,既把多个MemCache节点管理得井井有条,又保证数据能在各个节点间实现靠谱的分布式存储和同步更新,这可真是个挺让人挠头的技术难题啊。本文将围绕这一主题,结合代码实例,深入探讨并给出解决方案。 1. MemCache在分布式环境中的部署策略 首先,我们需要理解MemCache在分布式环境下的工作原理。MemCache这东西吧,本身并不具备跨节点数据一致性的功能,也就是说,每个节点都是个自给自足的小缓存个体,它们之间没有那种自动化同步数据的机制。所以,当我们在实际动手部署的时候,得想办法让这些工作量分散开,就像大家分担家务一样。这里我们可以用个很巧妙的方法,就叫“一致性哈希”,这个算法就像一个超级智能的分配器,能帮我们精准地判断每一份数据应该放在哪个小仓库(节点)里头,这样一来,所有的东西都能各归其位,整整齐齐。 python from pymemcache.client.hash import ConsistentHashRing nodes = [('node1', 11211), ('node2', 11211), ('node3', 11211)] ring = ConsistentHashRing(nodes) 使用一致性哈希决定key对应的节点 node, _ = ring.get_node('your_key') 2. 数据的分布式存储 上述的一致性哈希算法能够保证当新增或减少节点时,对已存在的大部分键值对的映射关系影响较小,从而实现数据的均衡分布。此外,咱们得牢牢记住一个大原则:如果有那么些关系紧密的数据兄弟,最好让它们挤在同一台MemCache服务器上,这样可以有效避免因为跨节点访问而产生的网络开销,懂我意思吧? 3. 同步更新问题及其解决思路 MemCache本身不具备数据同步功能,因此在分布式环境下进行数据更新时,需要通过应用层逻辑来保障一致性。常见的一种做法是“先更新数据库,再清除相关缓存”。 python 假设我们有一个更新用户信息的方法 def update_user_info(user_id, new_info): 先更新数据库 db.update_user(user_id, new_info) 清除MemCache中相关的缓存数据 memcached_client.delete(f'user_{user_id}') 另一种策略是引入消息队列,例如使用Redis Pub/Sub或者RabbitMQ等中间件,当数据库发生变更时,发布一条消息通知所有MemCache节点删除对应的缓存项。 4. MemCache节点的维护与监控 为了保证MemCache集群的稳定运行,我们需要定期对各个节点进行健康检查和性能监控,及时发现并处理可能出现的内存溢出、节点失效等问题。可以通过编写运维脚本定期检查,或者接入诸如Prometheus+Grafana这样的监控工具进行可视化管理。 bash 示例:简单的shell脚本检查MemCache节点状态 for node in $(cat memcache_nodes.txt); do echo "Checking ${node}..." telnet $node 11211 <<< stats | grep -q 'STAT bytes 0' if [ $? -eq 0 ]; then echo "${node} is down or not responding." else echo "${node} is up and running." fi done 总的来说,要在分布式环境中有效管理和维护多个MemCache节点,并实现数据的分布式存储与同步更新,不仅需要合理设计数据分布策略,还需要在应用层面对数据一致性进行把控,同时配合完善的节点监控和运维体系,才能确保整个缓存系统的高效稳定运行。在整个探险历程中,咱们得时刻动脑筋、动手尝试、灵活应变、优化咱的计划,这绝对是一个挑战多多、趣味盎然的过程,让人乐在其中。
2023-11-14 17:08:32
69
凌波微步
ZooKeeper
...。这不仅可能会让各个节点间的数据同步乱成一团糟,甚至可能把整个集群都搞得摇摇欲坠,稳定性大打折扣!这篇东西,我们打算从实实在在的案例开始聊起,再配上些代码实例,把这个问题掰开揉碎了讲明白,同时也会分享一些咱们想到的解决办法和对策,保证接地气儿! 2. ZooKeeper与磁盘I/O的关系 ZooKeeper作为一个高度依赖持久化存储的服务,它需要频繁地将内存中的数据变更同步到磁盘上以保证数据的一致性。当ZooKeeper节点的磁盘I/O性能不足或者磁盘空间紧张时,就容易触发此类错误。例如,当我们调用ZooKeeper的create()方法创建一个新的节点时: java ZooKeeper zookeeper = new ZooKeeper("localhost:2181", 3000, null); String path = "/my_znode"; String data = "Hello, ZooKeeper!"; zookeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 上述代码会在ZooKeeper服务器上创建一个持久化的节点并写入数据,这个过程就涉及到磁盘I/O操作。如果此时磁盘I/O出现问题,那么节点创建可能会失败,抛出异常。 3. 磁盘I/O错误的表现及影响 当ZooKeeper日志中频繁出现“Disk is full”、“No space left on device”或“I/O error”的警告时,表明存在磁盘I/O问题。这种状况会导致ZooKeeper没法顺利完成事务日志和快照文件的写入工作,这样一来,那些关键的数据持久化,还有服务器之间的选举、同步等核心功能都会受到连带影响。到了严重的时候,甚至会让整个服务直接罢工,无法提供服务。 4. 探究原因与解决方案 (1)磁盘空间不足 这是最直观的原因,可以通过清理不必要的数据文件或增加磁盘空间来解决。例如,定期清理ZooKeeper的事务日志和快照文件,可以使用自带的zkCleanup.sh脚本进行自动维护: bash ./zkCleanup.sh -n myServer1:2181/myZooKeeperCluster -p /data/zookeeper/version-2 (2)磁盘I/O性能瓶颈 如果磁盘读写速度过慢,也会影响ZooKeeper的正常运行。此时应考虑更换为高性能的SSD硬盘,或者优化磁盘阵列配置,提高I/O吞吐量。另外,一个蛮实用的办法就是灵活调整ZooKeeper的刷盘策略。比如说,我们可以适当地给syncLimit和tickTime这两个参数值加加油,让它们变大一些,这样一来,就能有效地降低刷盘操作的频率,让它不用那么频繁地进行写入操作,更贴近咱们日常的工作节奏啦。 (3)并发写入压力大 高并发场景下,大量写入请求可能会导致磁盘I/O瞬间飙升。对于这个问题,我们可以采取一些措施,比如运用负载均衡技术,让ZooKeeper集群的压力得到分散缓解,就像大家一起扛米袋,别让一个节点给累垮了。另外,针对实际情况,咱们也可以灵活调整,对ZooKeeper客户端API的调用来个“交通管制”,根据业务需求合理限流控制,避免拥堵,保持运行流畅。 5. 结论 面对ZooKeeper运行过程中出现的磁盘I/O错误,我们需要具体问题具体分析,结合监控数据、日志信息以及系统资源状况综合判断,采取相应措施进行优化。此外,良好的运维习惯和预防性管理同样重要,如定期检查磁盘空间、合理分配资源、优化系统配置等,都是避免这类问题的关键所在。说真的,ZooKeeper就相当于我们分布式系统的那个“底座大石头”,没它不行。只有把这块基石稳稳当当地砌好,咱们的系统才能健壮得像头牛,让人放心可靠地用起来。 以上内容,不仅是我在实践中积累的经验总结,也是我不断思考与探索的过程,希望对你理解和处理类似问题有所启发和帮助。记住,技术的魅力在于持续学习与实践,让我们一起在ZooKeeper的世界里乘风破浪!
2023-02-19 10:34:57
127
夜色朦胧
ZooKeeper
...种操作请求(比如创建节点、删除节点等)。嘿嘿,想象一下,这就好比一个超挤的电梯,已经装满了人,再有人想挤进去肯定会被拒之门外啦!ZooKeeper也一样,当它的小“队伍”排满了的时候,新来的请求就别想加塞儿了,直接就被它无情地“拒绝”了,然后还甩给你一个“异常”的小牌子,意思是说:“兄弟,这儿真的装不下了!”这种情况通常发生在高并发场景下,或者是网络延迟导致请求堆积。 为了更好地理解这个问题,我们可以看看下面这段代码: java import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.CreateMode; public class ZookeeperExample { public static void main(String[] args) throws Exception { // 创建ZooKeeper实例 ZooKeeper zk = new ZooKeeper("localhost:2181", 5000, event -> { System.out.println("ZooKeeper event: " + event); }); // 创建一个节点 String nodePath = zk.create("/testNode", "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); System.out.println("Node created at path: " + nodePath); // 关闭连接 zk.close(); } } 在这个简单的例子中,我们尝试创建一个ZooKeeper实例并创建一个节点。如果这个时候ZooKeeper的队列满了,就会抛出CommitQueueFullException。所以,接下来我们要做的就是想办法避免这种情况的发生。 --- 二、为什么会出现CommitQueueFullException? 在深入讨论解决方案之前,我觉得有必要先搞清楚为什么会发生这种异常。其实,这背后涉及到了ZooKeeper的一些设计细节。 首先,ZooKeeper的队列大小是由配置文件中的zookeeper.commitlog.capacity参数决定的。默认情况下,这个值是比较小的,可能只有几兆字节。想象一下,你的应用像一个忙碌的快递站,接到了无数订单(也就是那些请求)。但要是快递小哥忙得顾不上送货,订单就会越堆越多,很快整个站点就塞满了,连下一份订单都没地方放了! 其次,网络环境也是一个重要因素。有时候,客户端和服务端之间的网络延迟会导致请求堆积。就算客户端那边请求没那么频繁,但要是服务端反应慢了,照样会出问题啊。 最后,还有一个容易被忽视的原因就是客户端的连接数过多。每个连接都会占用一定的资源,包括内存和CPU。要是连上的用户太多了,但服务器的“体力”又不够强(比如内存、CPU之类的资源有限),那它就很容易“忙不过来”,导致请求都排着队等着,根本处理不完。 说到这里,我忍不住想吐槽一下自己曾经犯过的错误。嘿,有次我在测试环境里弄了个能扛大流量的程序,结果发现ZooKeeper老是蹦出个叫“CommitQueueFullException”的错误,烦得不行!我当时就纳闷了:“我明明设了个挺合理的线程池大小啊,怎么还出问题了呢?”后来一查才发现,坏事了,是客户端的连接数配少了,结果请求都堵在那儿了,就像高速公路堵车一样。真是教训深刻啊! --- 三、如何优雅地处理CommitQueueFullException? 既然知道了问题的根源,那接下来就要谈谈具体的解决办法了。我觉得可以从以下几个方面入手: 1. 调整队列大小 最直接的办法当然是增大队列的容量。通过修改zookeeper.commitlog.capacity参数,可以让ZooKeeper拥有更大的缓冲空间。其实嘛,这个方法也不是啥灵丹妙药,毕竟咱们手头的硬件资源就那么多,要是傻乎乎地把队列弄得太长,说不定反而会惹出别的麻烦,比如让系统跑得更卡之类的。 代码示例: properties zookeeper.commitlog.capacity=10485760 上面这段配置文件的内容表示将队列大小调整为10MB。你可以根据实际情况进行调整。 2. 优化客户端逻辑 很多时候,CommitQueueFullException并不是因为服务器的问题,而是客户端的请求模式不合理造成的。比如说,你是否可以合并多个小请求为一个大请求?或者是否可以采用批量操作的方式减少请求次数? 举个例子,假设你在做一个日志采集系统,每天需要向ZooKeeper写入成千上万个临时节点。与其每次都往一个节点里写东西,不如一口气往多个节点里写,这样能大大减少你发出的请求次数,省事儿又高效! 代码示例: java List nodesToCreate = Arrays.asList("/node1", "/node2", "/node3"); List createdNodes = zk.create("/batch/", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL, nodesToCreate.size()); System.out.println("Created nodes: " + createdNodes); 在这段代码中,我们一次性创建了三个临时节点,而不是分别调用三次create()方法。这样的做法不仅减少了请求次数,还提高了效率。 3. 增加服务器资源 如果以上两种方法都不能解决问题,那么可能就需要考虑升级服务器硬件了。比如增加内存、提升CPU性能,甚至更换更快的磁盘。当然,这通常是最后的选择,因为它涉及到成本和技术难度。 4. 使用异步API ZooKeeper提供了同步和异步两种API,其中异步API可以在一定程度上缓解CommitQueueFullException的问题。异步API可酷了!你提交个请求,它立马给你返回结果,根本不用傻等那个响应回来。这样一来啊,就相当于给任务队列放了个假,压力小了很多呢! 代码示例: java import org.apache.zookeeper.AsyncCallback.StringCallback; public class AsyncExample implements StringCallback { @Override public void processResult(int rc, String path, Object ctx, String name) { if (rc == 0) { System.out.println("Node created successfully at path: " + name); } else { System.err.println("Failed to create node with error code: " + rc); } } public static void main(String[] args) throws Exception { ZooKeeper zk = new ZooKeeper("localhost:2181", 5000, null); zk.createAsync("/asyncTest", "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new AsyncExample(), null); } } 在这段代码中,我们使用了createAsync()方法来异步创建节点。相比于同步版本,这种方式不会阻塞主线程,从而降低了队列满的风险。 --- 四、总结与展望 通过今天的探讨,我相信大家都对CommitQueueFullException有了更深刻的理解。嘿,别被这个错误吓到!其实啊,它也没那么可怕。只要你找到对的方法,保证分分钟搞定,就跟玩儿似的! 回顾整个过程,我觉得最重要的是要保持冷静和耐心。遇到技术难题的时候啊,别慌!先搞清楚它到底是个啥问题,就像剥洋葱一样,一层层搞明白本质。接着呢,就一步一步地去找解决的办法,慢慢来,总能找到出路的!就像攀登一座高山一样,每一步都需要脚踏实地。 最后,我想鼓励大家多动手实践。理论固然重要,但真正的成长来自于不断的尝试和失败。希望大家能够在实际项目中运用今天学到的知识,创造出更加优秀的应用! 好了,今天的分享就到这里啦!如果你还有什么疑问或者想法,欢迎随时交流哦~
2025-03-16 15:37:44
10
林中小径
转载文章
...系,构建图 计算图中节点的PageRank,注意是无向带权图 使用示例: 见 test/demo.py 词性标注 jieba.posseg.POSTokenizer(tokenizer=None) 新建自定义分词器,tokenizer 参数可指定内部使用的 jieba.Tokenizer 分词器。jieba.posseg.dt 为默认词性标注分词器。 标注句子分词后每个词的词性,采用和 ictclas 兼容的标记法。 除了jieba默认分词模式,提供paddle模式下的词性标注功能。paddle模式采用延迟加载方式,通过enable_paddle()安装paddlepaddle-tiny,并且import相关代码; 用法示例 >>> import jieba>>> import jieba.posseg as pseg>>> words = pseg.cut("我爱北京天安门") jieba默认模式>>> jieba.enable_paddle() 启动paddle模式。 0.40版之后开始支持,早期版本不支持>>> words = pseg.cut("我爱北京天安门",use_paddle=True) paddle模式>>> for word, flag in words:... print('%s %s' % (word, flag))...我 r爱 v北京 ns天安门 ns paddle模式词性标注对应表如下: paddle模式词性和专名类别标签集合如下表,其中词性标签 24 个(小写字母),专名类别标签 4 个(大写字母)。 标签 含义 标签 含义 标签 含义 标签 含义 n 普通名词 f 方位名词 s 处所名词 t 时间 nr 人名 ns 地名 nt 机构名 nw 作品名 nz 其他专名 v 普通动词 vd 动副词 vn 名动词 a 形容词 ad 副形词 an 名形词 d 副词 m 数量词 q 量词 r 代词 p 介词 c 连词 u 助词 xc 其他虚词 w 标点符号 PER 人名 LOC 地名 ORG 机构名 TIME 时间 并行分词 原理:将目标文本按行分隔后,把各行文本分配到多个 Python 进程并行分词,然后归并结果,从而获得分词速度的可观提升 基于 python 自带的 multiprocessing 模块,目前暂不支持 Windows 用法: jieba.enable_parallel(4) 开启并行分词模式,参数为并行进程数 jieba.disable_parallel() 关闭并行分词模式 例子:https://github.com/fxsjy/jieba/blob/master/test/parallel/test_file.py 实验结果:在 4 核 3.4GHz Linux 机器上,对金庸全集进行精确分词,获得了 1MB/s 的速度,是单进程版的 3.3 倍。 注意:并行分词仅支持默认分词器 jieba.dt 和 jieba.posseg.dt。 Tokenize:返回词语在原文的起止位置 注意,输入参数只接受 unicode 默认模式 result = jieba.tokenize(u'永和服装饰品有限公司')for tk in result:print("word %s\t\t start: %d \t\t end:%d" % (tk[0],tk[1],tk[2])) word 永和 start: 0 end:2word 服装 start: 2 end:4word 饰品 start: 4 end:6word 有限公司 start: 6 end:10 搜索模式 result = jieba.tokenize(u'永和服装饰品有限公司', mode='search')for tk in result:print("word %s\t\t start: %d \t\t end:%d" % (tk[0],tk[1],tk[2])) word 永和 start: 0 end:2word 服装 start: 2 end:4word 饰品 start: 4 end:6word 有限 start: 6 end:8word 公司 start: 8 end:10word 有限公司 start: 6 end:10 ChineseAnalyzer for Whoosh 搜索引擎 引用: from jieba.analyse import ChineseAnalyzer 用法示例:https://github.com/fxsjy/jieba/blob/master/test/test_whoosh.py 命令行分词 使用示例:python -m jieba news.txt > cut_result.txt 命令行选项(翻译): 使用: python -m jieba [options] filename结巴命令行界面。固定参数:filename 输入文件可选参数:-h, --help 显示此帮助信息并退出-d [DELIM], --delimiter [DELIM]使用 DELIM 分隔词语,而不是用默认的' / '。若不指定 DELIM,则使用一个空格分隔。-p [DELIM], --pos [DELIM]启用词性标注;如果指定 DELIM,词语和词性之间用它分隔,否则用 _ 分隔-D DICT, --dict DICT 使用 DICT 代替默认词典-u USER_DICT, --user-dict USER_DICT使用 USER_DICT 作为附加词典,与默认词典或自定义词典配合使用-a, --cut-all 全模式分词(不支持词性标注)-n, --no-hmm 不使用隐含马尔可夫模型-q, --quiet 不输出载入信息到 STDERR-V, --version 显示版本信息并退出如果没有指定文件名,则使用标准输入。 --help 选项输出: $> python -m jieba --helpJieba command line interface.positional arguments:filename input fileoptional arguments:-h, --help show this help message and exit-d [DELIM], --delimiter [DELIM]use DELIM instead of ' / ' for word delimiter; or aspace if it is used without DELIM-p [DELIM], --pos [DELIM]enable POS tagging; if DELIM is specified, use DELIMinstead of '_' for POS delimiter-D DICT, --dict DICT use DICT as dictionary-u USER_DICT, --user-dict USER_DICTuse USER_DICT together with the default dictionary orDICT (if specified)-a, --cut-all full pattern cutting (ignored with POS tagging)-n, --no-hmm don't use the Hidden Markov Model-q, --quiet don't print loading messages to stderr-V, --version show program's version number and exitIf no filename specified, use STDIN instead. 延迟加载机制 jieba 采用延迟加载,import jieba 和 jieba.Tokenizer() 不会立即触发词典的加载,一旦有必要才开始加载词典构建前缀字典。如果你想手工初始 jieba,也可以手动初始化。 import jiebajieba.initialize() 手动初始化(可选) 在 0.28 之前的版本是不能指定主词典的路径的,有了延迟加载机制后,你可以改变主词典的路径: jieba.set_dictionary('data/dict.txt.big') 例子: https://github.com/fxsjy/jieba/blob/master/test/test_change_dictpath.py 其他词典 占用内存较小的词典文件 https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.small 支持繁体分词更好的词典文件 https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.big 下载你所需要的词典,然后覆盖 jieba/dict.txt 即可;或者用 jieba.set_dictionary('data/dict.txt.big') 其他语言实现 结巴分词 Java 版本 作者:piaolingxue 地址:https://github.com/huaban/jieba-analysis 结巴分词 C++ 版本 作者:yanyiwu 地址:https://github.com/yanyiwu/cppjieba 结巴分词 Rust 版本 作者:messense, MnO2 地址:https://github.com/messense/jieba-rs 结巴分词 Node.js 版本 作者:yanyiwu 地址:https://github.com/yanyiwu/nodejieba 结巴分词 Erlang 版本 作者:falood 地址:https://github.com/falood/exjieba 结巴分词 R 版本 作者:qinwf 地址:https://github.com/qinwf/jiebaR 结巴分词 iOS 版本 作者:yanyiwu 地址:https://github.com/yanyiwu/iosjieba 结巴分词 PHP 版本 作者:fukuball 地址:https://github.com/fukuball/jieba-php 结巴分词 .NET(C) 版本 作者:anderscui 地址:https://github.com/anderscui/jieba.NET/ 结巴分词 Go 版本 作者: wangbin 地址: https://github.com/wangbin/jiebago 作者: yanyiwu 地址: https://github.com/yanyiwu/gojieba 结巴分词Android版本 作者 Dongliang.W 地址:https://github.com/452896915/jieba-android 友情链接 https://github.com/baidu/lac 百度中文词法分析(分词+词性+专名)系统 https://github.com/baidu/AnyQ 百度FAQ自动问答系统 https://github.com/baidu/Senta 百度情感识别系统 系统集成 Solr: https://github.com/sing1ee/jieba-solr 分词速度 1.5 MB / Second in Full Mode 400 KB / Second in Default Mode 测试环境: Intel® Core™ i7-2600 CPU @ 3.4GHz;《围城》.txt 常见问题 1. 模型的数据是如何生成的? 详见: https://github.com/fxsjy/jieba/issues/7 2. “台中”总是被切成“台 中”?(以及类似情况) P(台中) < P(台)×P(中),“台中”词频不够导致其成词概率较低 解决方法:强制调高词频 jieba.add_word('台中') 或者 jieba.suggest_freq('台中', True) 3. “今天天气 不错”应该被切成“今天 天气 不错”?(以及类似情况) 解决方法:强制调低词频 jieba.suggest_freq(('今天', '天气'), True) 或者直接删除该词 jieba.del_word('今天天气') 4. 切出了词典中没有的词语,效果不理想? 解决方法:关闭新词发现 jieba.cut('丰田太省了', HMM=False) jieba.cut('我们中出了一个叛徒', HMM=False) 更多问题请点击:https://github.com/fxsjy/jieba/issues?sort=updated&state=closed 修订历史 https://github.com/fxsjy/jieba/blob/master/Changelog jieba “Jieba” (Chinese for “to stutter”) Chinese text segmentation: built to be the best Python Chinese word segmentation module. Features Support three types of segmentation mode: Accurate Mode attempts to cut the sentence into the most accurate segmentations, which is suitable for text analysis. Full Mode gets all the possible words from the sentence. Fast but not accurate. Search Engine Mode, based on the Accurate Mode, attempts to cut long words into several short words, which can raise the recall rate. Suitable for search engines. Supports Traditional Chinese Supports customized dictionaries MIT License Online demo http://jiebademo.ap01.aws.af.cm/ (Powered by Appfog) Usage Fully automatic installation: easy_install jieba or pip install jieba Semi-automatic installation: Download http://pypi.python.org/pypi/jieba/ , run python setup.py install after extracting. Manual installation: place the jieba directory in the current directory or python site-packages directory. import jieba. Algorithm Based on a prefix dictionary structure to achieve efficient word graph scanning. Build a directed acyclic graph (DAG) for all possible word combinations. Use dynamic programming to find the most probable combination based on the word frequency. For unknown words, a HMM-based model is used with the Viterbi algorithm. Main Functions Cut The jieba.cut function accepts three input parameters: the first parameter is the string to be cut; the second parameter is cut_all, controlling the cut mode; the third parameter is to control whether to use the Hidden Markov Model. jieba.cut_for_search accepts two parameter: the string to be cut; whether to use the Hidden Markov Model. This will cut the sentence into short words suitable for search engines. The input string can be an unicode/str object, or a str/bytes object which is encoded in UTF-8 or GBK. Note that using GBK encoding is not recommended because it may be unexpectly decoded as UTF-8. jieba.cut and jieba.cut_for_search returns an generator, from which you can use a for loop to get the segmentation result (in unicode). jieba.lcut and jieba.lcut_for_search returns a list. jieba.Tokenizer(dictionary=DEFAULT_DICT) creates a new customized Tokenizer, which enables you to use different dictionaries at the same time. jieba.dt is the default Tokenizer, to which almost all global functions are mapped. Code example: segmentation encoding=utf-8import jiebaseg_list = jieba.cut("我来到北京清华大学", cut_all=True)print("Full Mode: " + "/ ".join(seg_list)) 全模式seg_list = jieba.cut("我来到北京清华大学", cut_all=False)print("Default Mode: " + "/ ".join(seg_list)) 默认模式seg_list = jieba.cut("他来到了网易杭研大厦")print(", ".join(seg_list))seg_list = jieba.cut_for_search("小明硕士毕业于中国科学院计算所,后在日本京都大学深造") 搜索引擎模式print(", ".join(seg_list)) Output: [Full Mode]: 我/ 来到/ 北京/ 清华/ 清华大学/ 华大/ 大学[Accurate Mode]: 我/ 来到/ 北京/ 清华大学[Unknown Words Recognize] 他, 来到, 了, 网易, 杭研, 大厦 (In this case, "杭研" is not in the dictionary, but is identified by the Viterbi algorithm)[Search Engine Mode]: 小明, 硕士, 毕业, 于, 中国, 科学, 学院, 科学院, 中国科学院, 计算, 计算所, 后, 在, 日本, 京都, 大学, 日本京都大学, 深造 Add a custom dictionary Load dictionary Developers can specify their own custom dictionary to be included in the jieba default dictionary. Jieba is able to identify new words, but you can add your own new words can ensure a higher accuracy. Usage: jieba.load_userdict(file_name) file_name is a file-like object or the path of the custom dictionary The dictionary format is the same as that of dict.txt: one word per line; each line is divided into three parts separated by a space: word, word frequency, POS tag. If file_name is a path or a file opened in binary mode, the dictionary must be UTF-8 encoded. The word frequency and POS tag can be omitted respectively. The word frequency will be filled with a suitable value if omitted. For example: 创新办 3 i云计算 5凱特琳 nz台中 Change a Tokenizer’s tmp_dir and cache_file to specify the path of the cache file, for using on a restricted file system. Example: 云计算 5李小福 2创新办 3[Before]: 李小福 / 是 / 创新 / 办 / 主任 / 也 / 是 / 云 / 计算 / 方面 / 的 / 专家 /[After]: 李小福 / 是 / 创新办 / 主任 / 也 / 是 / 云计算 / 方面 / 的 / 专家 / Modify dictionary Use add_word(word, freq=None, tag=None) and del_word(word) to modify the dictionary dynamically in programs. Use suggest_freq(segment, tune=True) to adjust the frequency of a single word so that it can (or cannot) be segmented. Note that HMM may affect the final result. Example: >>> print('/'.join(jieba.cut('如果放到post中将出错。', HMM=False)))如果/放到/post/中将/出错/。>>> jieba.suggest_freq(('中', '将'), True)494>>> print('/'.join(jieba.cut('如果放到post中将出错。', HMM=False)))如果/放到/post/中/将/出错/。>>> print('/'.join(jieba.cut('「台中」正确应该不会被切开', HMM=False)))「/台/中/」/正确/应该/不会/被/切开>>> jieba.suggest_freq('台中', True)69>>> print('/'.join(jieba.cut('「台中」正确应该不会被切开', HMM=False)))「/台中/」/正确/应该/不会/被/切开 Keyword Extraction import jieba.analyse jieba.analyse.extract_tags(sentence, topK=20, withWeight=False, allowPOS=()) sentence: the text to be extracted topK: return how many keywords with the highest TF/IDF weights. The default value is 20 withWeight: whether return TF/IDF weights with the keywords. The default value is False allowPOS: filter words with which POSs are included. Empty for no filtering. jieba.analyse.TFIDF(idf_path=None) creates a new TFIDF instance, idf_path specifies IDF file path. Example (keyword extraction) https://github.com/fxsjy/jieba/blob/master/test/extract_tags.py Developers can specify their own custom IDF corpus in jieba keyword extraction Usage: jieba.analyse.set_idf_path(file_name) file_name is the path for the custom corpus Custom Corpus Sample:https://github.com/fxsjy/jieba/blob/master/extra_dict/idf.txt.big Sample Code:https://github.com/fxsjy/jieba/blob/master/test/extract_tags_idfpath.py Developers can specify their own custom stop words corpus in jieba keyword extraction Usage: jieba.analyse.set_stop_words(file_name) file_name is the path for the custom corpus Custom Corpus Sample:https://github.com/fxsjy/jieba/blob/master/extra_dict/stop_words.txt Sample Code:https://github.com/fxsjy/jieba/blob/master/test/extract_tags_stop_words.py There’s also a TextRank implementation available. Use: jieba.analyse.textrank(sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v')) Note that it filters POS by default. jieba.analyse.TextRank() creates a new TextRank instance. Part of Speech Tagging jieba.posseg.POSTokenizer(tokenizer=None) creates a new customized Tokenizer. tokenizer specifies the jieba.Tokenizer to internally use. jieba.posseg.dt is the default POSTokenizer. Tags the POS of each word after segmentation, using labels compatible with ictclas. Example: >>> import jieba.posseg as pseg>>> words = pseg.cut("我爱北京天安门")>>> for w in words:... print('%s %s' % (w.word, w.flag))...我 r爱 v北京 ns天安门 ns Parallel Processing Principle: Split target text by line, assign the lines into multiple Python processes, and then merge the results, which is considerably faster. Based on the multiprocessing module of Python. Usage: jieba.enable_parallel(4) Enable parallel processing. The parameter is the number of processes. jieba.disable_parallel() Disable parallel processing. Example: https://github.com/fxsjy/jieba/blob/master/test/parallel/test_file.py Result: On a four-core 3.4GHz Linux machine, do accurate word segmentation on Complete Works of Jin Yong, and the speed reaches 1MB/s, which is 3.3 times faster than the single-process version. Note that parallel processing supports only default tokenizers, jieba.dt and jieba.posseg.dt. Tokenize: return words with position The input must be unicode Default mode result = jieba.tokenize(u'永和服装饰品有限公司')for tk in result:print("word %s\t\t start: %d \t\t end:%d" % (tk[0],tk[1],tk[2])) word 永和 start: 0 end:2word 服装 start: 2 end:4word 饰品 start: 4 end:6word 有限公司 start: 6 end:10 Search mode result = jieba.tokenize(u'永和服装饰品有限公司',mode='search')for tk in result:print("word %s\t\t start: %d \t\t end:%d" % (tk[0],tk[1],tk[2])) word 永和 start: 0 end:2word 服装 start: 2 end:4word 饰品 start: 4 end:6word 有限 start: 6 end:8word 公司 start: 8 end:10word 有限公司 start: 6 end:10 ChineseAnalyzer for Whoosh from jieba.analyse import ChineseAnalyzer Example: https://github.com/fxsjy/jieba/blob/master/test/test_whoosh.py Command Line Interface $> python -m jieba --helpJieba command line interface.positional arguments:filename input fileoptional arguments:-h, --help show this help message and exit-d [DELIM], --delimiter [DELIM]use DELIM instead of ' / ' for word delimiter; or aspace if it is used without DELIM-p [DELIM], --pos [DELIM]enable POS tagging; if DELIM is specified, use DELIMinstead of '_' for POS delimiter-D DICT, --dict DICT use DICT as dictionary-u USER_DICT, --user-dict USER_DICTuse USER_DICT together with the default dictionary orDICT (if specified)-a, --cut-all full pattern cutting (ignored with POS tagging)-n, --no-hmm don't use the Hidden Markov Model-q, --quiet don't print loading messages to stderr-V, --version show program's version number and exitIf no filename specified, use STDIN instead. Initialization By default, Jieba don’t build the prefix dictionary unless it’s necessary. This takes 1-3 seconds, after which it is not initialized again. If you want to initialize Jieba manually, you can call: import jiebajieba.initialize() (optional) You can also specify the dictionary (not supported before version 0.28) : jieba.set_dictionary('data/dict.txt.big') Using Other Dictionaries It is possible to use your own dictionary with Jieba, and there are also two dictionaries ready for download: A smaller dictionary for a smaller memory footprint: https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.small There is also a bigger dictionary that has better support for traditional Chinese (繁體): https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.big By default, an in-between dictionary is used, called dict.txt and included in the distribution. In either case, download the file you want, and then call jieba.set_dictionary('data/dict.txt.big') or just replace the existing dict.txt. Segmentation speed 1.5 MB / Second in Full Mode 400 KB / Second in Default Mode Test Env: Intel® Core™ i7-2600 CPU @ 3.4GHz;《围城》.txt 本篇文章为转载内容。原文链接:https://blog.csdn.net/yegeli/article/details/107246661。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-02 10:38:37
500
转载
AngularJS
...get('/api/data') .then(function(response) { $scope.data = response.data; }); }); 在这个例子中,我们在控制器中注入了$http服务,并且使用$http.get方法发送了一个GET请求到'/api/data'这个URL。当服务器返回响应时,我们会在.then方法中处理这个响应。 三、使用$http服务发送POST请求 除了GET请求,我们还可以使用$http服务发送POST请求。下面是一个例子: javascript angular.module('myApp') .controller('MyCtrl', function($scope, $http) { $scope.submitData = function() { var data = {name: $scope.name, email: $scope.email}; $http.post('/api/submit', data) .then(function(response) { alert('Data submitted successfully!'); }); }; }); 在这个例子中,我们在提交数据之前先获取了表单中的数据,然后使用$http.post方法发送了一个POST请求到'/api/submit'这个URL,并将数据作为请求体发送出去。当服务器返回响应时,我们会弹出一个成功的提示框。 四、总结 总的来说,虽然AngularJS提供了很多方便的工具和服务,但是在非AngularJS的环境中也可以使用$http服务。经过以上这几个步骤,我真心相信你现在已经有十足的把握,在没有AngularJS的环境里也能灵活运用$http服务啦,妥妥的! 最后,我要强调的是,虽然$http服务可以让我们更方便地处理HTTP请求和响应,但是在实际开发中,我们也应该尽可能地避免直接使用原始的JavaScript库或者API。这样搞的话,不仅会让我们的代码变得乱七八糟、纠结复杂,还会让以后维护和扩展代码变得像啃硬骨头一样难,可费劲儿了。
2023-05-14 10:40:55
362
繁华落尽-t
VUE
.../api/some-data') .then(response => { console.log('数据获取成功', response.data); }) .catch(error => { if (error.response.status === 401) { console.error('401错误:未授权'); // 这里可以跳转到登录页面 window.location.href = '/login'; } else { console.error('其他错误', error); } }); 这种方式虽然能解决问题,但每次请求都要重复这段代码,显得不够优雅。我们需要一个更通用的方法来处理这个问题。 3. 使用拦截器 一次设置,处处生效 Vue项目中,我们通常会使用axios作为HTTP客户端。Axios有个很酷的拦截器功能,让我们可以在请求发出前后做一些全局的处理,特别方便。我们可以在main.js中设置拦截器: javascript import Vue from 'vue'; import App from './App.vue'; import axios from 'axios'; import router from './router'; Vue.config.productionTip = false; // 设置axios的拦截器 axios.interceptors.response.use( response => response, error => { if (error.response.status === 401) { // 处理401错误 console.error('401错误:未授权'); // 跳转到登录页面 router.push({ name: 'Login' }); } return Promise.reject(error); } ); new Vue({ router, render: h => h(App) }).$mount('app'); 这样,无论你在项目的哪个地方发起请求,只要遇到401错误,都会自动跳转到登录页面。是不是很酷? 4. 处理边缘情况 重新登录后跳转回原页面 但是,如果用户在登录后还想回到之前访问的页面怎么办?我们可以利用路由的参数来传递信息。例如,在跳转到登录页时,我们可以带上当前的路由路径: javascript router.push({ name: 'Login', query: { redirect: router.currentRoute.fullPath } }); 然后在登录成功的回调中,我们可以根据这个参数进行跳转: javascript methods: { login() { // 登录逻辑 axios.post('/api/login', this.credentials) .then(() => { const redirect = this.$route.query.redirect; if (redirect) { this.$router.push(redirect); } else { this.$router.push('/'); } }) .catch(error => { console.error('登录失败', error); }); } } 这样一来,用户在登录成功后就能返回到之前访问的页面了。 5. 总结与反思 通过以上的讨论,我们看到了如何在Vue项目中处理401未授权错误。从一开始的简单应对,到后来用axios拦截器,最后搞定那些特殊状况,每一步都让我们离那个完美的解决办法更近了点儿。在这过程中,我真是领悟到,编程可不只是敲代码那么简单,还得想到各种可能出现的状况,然后还得想出漂亮利索的解决办法。 希望这篇文章对你有所帮助,如果你有任何问题或更好的建议,欢迎在评论区留言交流!
2025-01-23 15:55:50
29
灵动之光
NodeJS
Node.js 与 WebSocket 构建实时监控面板 1. 开头 为什么选择 Node.js 和 WebSocket? 大家好!今天咱们聊聊如何用 Node.js 和 WebSocket 搭建一个实时监控面板。说实话,这事儿我琢磨了好久。作为一个前端开发爱好者,我一直对“实时”这个概念特别着迷。比如说,你点开一个网页,嚯!服务器跑得怎么样、数据库忙不忙,这些事儿一下子就清清楚楚地摆在眼前,还能隔空摆弄一下设备呢!这感觉,简直爽到飞起有木有? 但问题是,要实现这种功能并不简单。想象一下,以前我们用老式的网页加载方式,就像打电话问朋友“嘿,有啥新鲜事儿没?”然后挂掉电话等对方回拨告诉你答案。问题是,如果你想知道最新消息,就得一直重复这个过程——不停地挂电话再拨号,也就是不停刷新页面,才能看到有没有新东西蹦出来。这显然不是最优解。而 WebSocket 就不一样了,它是一种全双工通信协议,可以让客户端和服务端随时互相推送消息,简直是实时应用的最佳拍档! 说到 Node.js,它天生就擅长处理异步事件流,再加上强大的生态系统(比如 Express、Socket.IO 等),简直就是为实时应用量身定制的工具。所以,今天我们就用 Node.js + WebSocket 来做一个简单的实时监控面板,顺便分享一下我的一些心得。 --- 2. 第一步 搭建基础环境 首先,我们需要准备开发环境。Node.js 的安装非常简单,去官网下载对应版本就行。安装完后,用 node -v 和 npm -v 验证是否成功。如果这两个命令都能正常输出版本号,那就说明环境配置好了。 接下来,我们创建项目文件夹,并初始化 npm: bash mkdir real-time-monitor cd real-time-monitor npm init -y 然后安装必要的依赖包。这里我们用到两个核心库:Express 和 ws(WebSocket 库)。Express 是用来搭建 HTTP 服务的,ws 则专门用于 WebSocket 通信。 bash npm install express ws 接下来,我们写一个最基础的 HTTP 服务,确保环境能正常工作: javascript // server.js const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(Server is running on port ${PORT}); }); 保存文件后运行 node server.js,然后在浏览器输入 http://localhost:3000,应该能看到 “Hello World!”。到这里,我们的基本框架已经搭好了,是不是感觉还挺容易的? --- 3. 第二步 引入 WebSocket 现在我们有了一个 HTTP 服务,接下来该让 WebSocket 上场了。WebSocket 的好处就是能在浏览器和服务器之间直接搭起一条“高速公路”,不用老是像发短信那样频繁地丢 HTTP 请求过去,省时又高效!为了方便,我们可以直接用 ws 库来实现。 修改 server.js 文件,添加 WebSocket 相关代码: javascript // server.js const express = require('express'); const WebSocket = require('ws'); const app = express(); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { console.log('A client connected!'); // 接收来自客户端的消息 ws.on('message', (message) => { console.log(Received message => ${message}); ws.send(You said: ${message}); }); // 当客户端断开时触发 ws.on('close', () => { console.log('Client disconnected.'); }); }); app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(HTTP Server is running on port ${PORT}); }); 这段代码做了几件事: 1. 创建了一个 WebSocket 服务器,监听端口 8080。 2. 当客户端连接时,打印日志并等待消息。 3. 收到消息后,会回传给客户端。 4. 如果客户端断开连接,也会记录日志。 为了让浏览器能连接到 WebSocket 服务器,我们还需要一个简单的 HTML 页面作为客户端入口: html Real-Time Monitor WebSocket Test Send Message 这段 HTML 代码包含了一个简单的聊天界面,用户可以在输入框中输入内容并通过 WebSocket 发送到服务器,同时也能接收到服务器返回的信息。跑完 node server.js 之后,别忘了打开浏览器,去 http://localhost:3000 看一眼,看看它是不是能正常转起来。 --- 4. 第三步 扩展功能——实时监控数据 现在我们的 WebSocket 已经可以正常工作了,但还不能算是一个真正的监控面板。为了让它更实用一点,咱们不妨假装弄点监控数据玩玩,像CPU用得多不多、内存占了百分之多少之类的。 首先,我们需要一个生成随机监控数据的函数: javascript function generateRandomMetrics() { return { cpuUsage: Math.random() 100, memoryUsage: Math.random() 100, diskUsage: Math.random() 100 }; } 然后,在 WebSocket 连接中定时向客户端推送这些数据: javascript wss.on('connection', (ws) => { console.log('A client connected!'); setInterval(() => { const metrics = generateRandomMetrics(); ws.send(JSON.stringify(metrics)); }, 1000); // 每秒发送一次 ws.on('close', () => { console.log('Client disconnected.'); }); }); 客户端需要解析接收到的数据,并动态更新页面上的信息。我们可以稍微改造一下 HTML 和 JavaScript: html CPU Usage: Memory Usage: Disk Usage: javascript socket.onmessage = (event) => { const metrics = JSON.parse(event.data); document.getElementById('cpuProgress').value = metrics.cpuUsage; document.getElementById('memoryProgress').value = metrics.memoryUsage; document.getElementById('diskProgress').value = metrics.diskUsage; const messagesDiv = document.getElementById('messages'); messagesDiv.innerHTML += Metrics updated. ; }; 这样,每秒钟都会从服务器获取一次监控数据,并在页面上以进度条的形式展示出来。是不是很酷? --- 5. 结尾 总结与展望 通过这篇文章,我们从零开始搭建了一个基于 Node.js 和 WebSocket 的实时监控面板。别看它现在功能挺朴素的,但这东西一出手就让人觉得,WebSocket 在实时互动这块儿真的大有可为啊!嘿,听我说!以后啊,你完全可以接着把这个项目捯饬得更酷一些。比如说,弄点新鲜玩意儿当监控指标,让用户用起来更爽,或者直接把它整到真正的生产环境里去,让它发挥大作用! 其实开发的过程就像拼图一样,有时候你会遇到困难,但只要一点点尝试和调整,总会找到答案。希望这篇文章能给你带来灵感,也欢迎你在评论区分享你的想法和经验! 最后,如果你觉得这篇文章对你有帮助,记得点个赞哦!😄 --- 完
2025-05-06 16:24:48
71
清风徐来
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
tail -f /var/log/messages
- 实时查看日志文件新增内容。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
2023-04-28
2023-08-09
2023-06-18
2023-04-14
2023-02-18
2023-04-17
2024-01-11
2023-10-03
2023-09-09
2023-06-13
2023-08-07
2023-03-11
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"