前端技术
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
[POST]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
VUE
...iv class="posts"><ul><li v-for="post in posts"><h2>{ { post.title } }</h2><p>{ { post.content } }</p></li></ul></div><footer><small>{ { currentYear } }</small></footer></div></template><script>export default { name: 'App', data() { return { blogTitle: 'My Blog', posts: [ { title: 'First Post', content: 'This is my very first Vue post, welcome!' }, { title: 'Second Post', content: 'This is my second post, much cooler than the first one!' } ] } }, computed: { currentYear() { return new Date().getFullYear() } } } </script> 这是一个基础的Vue博客制作模版,其中有三个主要部分:头部、内容和页脚。使用Vue的双向绑定技术可以快速展现页面,而使用v-for命令可以容易地循环帖子并展现相应的内容。 在博客制作中,Vue还有很多其他特性可以使用,如路由、状态管理和动画效果等。凭借灵活地使用这些技术,可以实现一个完备、当代的博客网站。
2023-02-07 16:45:07
118
数据库专家
ReactJS
...onst fetchPost = async (postId) => { const response = await fetch(https://jsonplaceholder.typicode.com/posts/${postId}); return response.json(); }; 这里我们用了一个公共的JSONPlaceholder API来获取假数据。当然,在生产环境中你应该替换为自己的API地址。 第二步:定义数据加载逻辑 现在我们需要让React知道如何加载这个数据。我们可以创建一个专门用于数据加载的组件,比如叫PostLoader: jsx // PostLoader.js import React, { useState, useEffect } from 'react'; const PostLoader = ({ postId }) => { const [post, setPost] = useState(null); const [error, setError] = useState(null); useEffect(() => { let isMounted = true; fetchPost(postId) .then((data) => { if (isMounted) { setPost(data); } }) .catch((err) => { if (isMounted) { setError(err); } }); return () => { isMounted = false; }; }, [postId]); if (error) { throw new Error('Failed to load post'); } return post; }; export default PostLoader; 这段代码的核心在于throw new Error这一行。当我们遇到错误时,不是简单地返回错误提示,而是直接抛出异常。这是为了让Suspense能够捕获到它并执行后备渲染。 第三步:整合Suspense 最后一步就是将所有东西组合起来,让Suspense接管整个流程: jsx // App.js import React, { Suspense } from 'react'; import PostLoader from './PostLoader'; const PostDetails = ({ postId }) => { const post = ; return ( {post.title} {post.body} ); }; const App = () => { return ( 欢迎来到我的博客 正在加载文章... }> ); }; export default App; 在这个例子中,会确保如果未能及时加载数据,它会显示“正在加载文章...”。 --- 4. 高级玩法 动态导入与代码分割 除了数据获取之外,Suspense还可以帮助我们实现代码分割。这就相当于你把那些不怎么常用的功能模块“藏”起来,等需要用到的时候再慢慢加载,这样主页面就能跑得飞快啦! 例如,如果你想按需加载某个功能模块,可以这样做: javascript // LazyComponent.js const LazyComponent = React.lazy(() => import('./LazyModule')); function App() { return ( 主页面 加载中... }> ); } 在这里,React.lazy配合Suspense实现了动态导入。当用户访问包含的部分时,React会自动加载对应的模块文件。 --- 5. 总结与反思 好了,到这里我们已经掌握了如何使用Suspense进行数据获取的基本方法。虽然它看起来很简单,但实际上背后涉及了很多复杂的机制。比如,它是如何知道哪些组件需要等待的?又是如何优雅地处理错误的? 我个人觉得,Suspense最大的优点就在于它让开发者摆脱了手动状态管理的束缚,让我们可以更专注于用户体验本身。不过呢,这里还是得提防点小问题,比如说可能会让程序跑得没那么顺畅,还有就是对那些老项目的支持可能没那么友好。 总之,Suspense是一个非常强大的工具,但它并不适合所有场景。作为开发者,我们需要根据实际情况权衡利弊,合理选择是否采用它。 好了,今天的分享就到这里啦!如果你有任何疑问或者想法,欢迎随时留言交流哦~ 😊
2025-04-12 16:09:18
86
蝶舞花间
Go Gin
...各种 GET、POST、PUT、DELETE 混在一起,代码读起来就像一团乱麻。你是不是经常在想:“这接口怎么又加了一个参数?是哪个地方调用了它?” 其实啊,这些问题都可以通过一个小小的工具来解决——Gin 的 Group 功能。 简单来说,Group 就是一个用来分组路由的功能,它能让你把相关的路由放在一起,让代码看起来更清晰,维护起来也更方便。这就跟咱们整理衣柜时,把夏天的衣服和冬天的衣服分开放一个道理,这样脑子一下子就有谱了。 不过呢,很多人可能觉得 Group 功能没啥特别的,其实不然。它不仅能帮你理清思路,还能提高代码的可读性和可维护性。接下来,我们就一起来看看它是怎么工作的吧! --- 2. 初识Group 基础用法 首先,咱们得知道 Group 是啥。简单来说啊,这 Group 就像是给路由套了个“外衣”,这么一来,咱们就能把那些长得像、用法类似的路由整到一块儿去了,是不是特方便?比如,所有跟用户相关的接口,我们就可以放在同一个组里。 示例1:创建一个简单的 Group go package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { r := gin.Default() // 创建一个用户组 userGroup := r.Group("/users") { // 用户注册接口 userGroup.POST("/register", func(c gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "User registered successfully"}) }) // 用户登录接口 userGroup.POST("/login", func(c gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "Login successful"}) }) } // 启动服务 r.Run(":8080") } 在这段代码里,我们先用 r.Group("/users") 创建了一个名为 /users 的路由组。然后在这个组里定义了两个接口:/register 和 /login。这样一来,所有与用户相关的接口都集中在一个地方,是不是感觉清爽多了? --- 3. 深入探讨 嵌套分组 当然啦,Group 不仅仅能用来分一级路由,还可以嵌套分组,这就像是在衣柜里再加几个小抽屉一样,分类更细致了。 示例2:嵌套分组 go package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { r := gin.Default() // 创建一个主路由组 mainGroup := r.Group("/api") { // 子路由组:用户相关 userGroup := mainGroup.Group("/users") { userGroup.GET("/", func(c gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "List all users"}) }) // 获取单个用户信息 userGroup.GET("/:id", func(c gin.Context) { id := c.Param("id") c.JSON(http.StatusOK, gin.H{"message": "User info", "id": id}) }) } // 子路由组:订单相关 orderGroup := mainGroup.Group("/orders") { orderGroup.POST("/", func(c gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "Order created successfully"}) }) orderGroup.GET("/", func(c gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "List all orders"}) }) } } r.Run(":8080") } 在这个例子中,我们首先创建了一个 /api 的主路由组,然后在这个主组下面分别创建了 /users 和 /orders 两个子路由组。这样的结构是不是更有条理了?尤其是当你项目变得复杂时,这种分层结构会让你少走很多弯路。 --- 4. 实战技巧 动态前缀与中间件 除了分组之外,Group 还支持动态前缀和中间件绑定。哈哈,这个功能超实用啊!就像是给一帮小伙伴设了个统一的“群规”,所有成员都自动遵守。不过呢,要是哪天你想让某个小组玩点不一样的,比如换个新名字前缀啥的,也能随时调整,特别方便! 示例3:动态前缀与中间件 go package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { r := gin.Default() // 设置全局中间件 r.Use(func(c gin.Context) { c.Set("auth", "token") c.Next() }) // 创建一个用户组,并绑定中间件 userGroup := r.Group("/v1/users", func(c gin.Context) { token := c.MustGet("auth").(string) if token != "admin" { c.AbortWithStatus(http.StatusUnauthorized) return } }) // 用户注册接口 userGroup.POST("/register", func(c gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "User registered successfully"}) }) // 用户登录接口 userGroup.POST("/login", func(c gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "Login successful"}) }) r.Run(":8080") } 在这个例子中,我们为 /v1/users 组绑定了一个中间件,只有携带正确令牌的请求才能访问该组下的接口。这种方式特别适合处理权限控制问题,避免了重复编写相同逻辑的麻烦。 --- 5. 总结 拥抱清晰的代码 兄弟们,路由分组真的是一项非常实用的技术。它不仅能让我们的代码更加整洁,还能大大提升开发效率。试想一下,如果你接手一个没有任何分组的项目,面对成千上万行杂乱无章的代码,你会不会崩溃? 所以啊,从今天开始,不管你的项目多大,都要养成使用 Group 的好习惯。不管你是弄个小玩意儿,还是搞那种复杂得让人头大的微服务架构,只要分组分得好,就能省不少劲儿,效率蹭蹭往上涨!记住,代码不仅仅是给机器看的,更是给人看的。清晰的代码,就是对同行最大的尊重! 最后,希望这篇文章能帮到你们。如果你们还有什么疑问或者更好的实践方法,欢迎留言交流哦!一起进步,一起成长!
2025-04-10 16:19:55
42
青春印记
转载文章
...一代加密标准PQC(Post-Quantum Cryptography)的第四轮候选算法名单,其中多个方案如CRYSTALS-Kyber、NTRU Prime等都基于 lattice-based cryptography(格密码学),而这类密码体制的核心构建部分就涉及到了高效解决特定类型的同余方程问题。 此外,区块链技术中的智能合约验证机制也常利用同余方程与模运算进行安全高效的签名确认。以太坊2.0信标链采用的BLS签名方案,其背后就运用了扩展欧几里得算法来计算密钥对生成和签名验证过程中的关键参数。 因此,深入理解和熟练掌握同余方程以及扩展欧几里得算法不仅能帮助我们在学术研究和算法竞赛中取得优势,更是在未来信息技术安全、数据加密等领域保持竞争力的关键要素。随着量子计算机的发展,对经典密码学构成挑战的同时,也为这些基础数学工具的应用提供了更为广阔的研究空间和实际需求。
2023-02-18 16:22:02
1154
转载
JSON
... requests.post('http://example.com/api/users', headers=headers, data=json.dumps(data)) assert response.status_code == 200 assert response.json().get('success') is True 在这个例子中,我们使用了Python中的requests库,来仿照发送一个POST方式请求。我们设置了请求的headers和data,借助于json.dumps()函数将data转换为JSON格式。在请求结束后,我们通过assert断言判断请求的返回状态码和JSON数据是否符合预期。如果测试案例执行成功,则代表接口调用正常。 总的来说,JSON程序化测试可以帮助我们实现快速、可靠和缩短测试时间等诸多优点。同时需要注意JSON格式的数据,需要符合规范,否则在数据处理环节中可能会出现意想不到的错误。
2023-12-07 16:32:59
499
软件工程师
AngularJS
...nfig); }, post: function(url, data, config) { return instance.post(url, data, config); } }; }); 然后,在我们的控制器中,只需要注入并使用这个工厂函数即可: javascript angular.module('myApp').controller('MyCtrl', function($scope, $httpInstance) { $httpInstance.get('/api/data') .then(function(response) { $scope.data = response.data; }); }); 五、总结 在使用AngularJS时,我们应该尽可能地遵循其设计原则,避免滥用$http服务。同时呢,咱们也得摸清楚AngularJS里的各种服务和功能点,这样才能更好地把它们用起来,让我们的开发效率蹭蹭往上涨哈! 在遇到问题时,我们应该积极寻找解决方案,并不断学习和探索。这样讲吧,只有当我们真正做到这一点,才能算得上是个名副其实的AngularJS大神,才能确保自己在这个日新月异的技术江湖中始终保持领先地位,不被淘汰。
2023-05-03 11:33:37
515
灵动之光-t
AngularJS
...用$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
Apache Atlas
...get): 发送POST请求,将元数据同步到Atlas中 response = requests.post( f"{self.atlasserver}/metadata/{source}/sync", json={ "target": target } ) 检查响应状态码,判断是否成功 if response.status_code != 200: raise Exception(f"Failed to sync metadata from {source} to {target}") def add_label(self, entity, label): 发送PUT请求,添加标签 response = requests.put( f"{self.atlasserver}/metadata/{entity}/labels", json={ "label": label } ) 检查响应状态码,判断是否成功 if response.status_code != 200: raise Exception(f"Failed to add label {label} to {entity}") python 定义一个类,用于处理机器学习 class MachineLearning: def __init__(self, atlasserver): self.atlasserver = atlasserver def train_model(self, dataset): 发送POST请求,训练模型 response = requests.post( f"{self.atlasserver}/machinelearning/train", json={ "dataset": dataset } ) 检查响应状态码,判断是否成功 if response.status_code != 200: raise Exception(f"Failed to train model") def predict_error(self, data): 发送POST请求,预测错误 response = requests.post( f"{self.atlasserver}/machinelearning/predict", json={ "data": data } ) 检查响应状态码,判断是否成功 if response.status_code != 200: raise Exception(f"Failed to predict error") 五、总结 总的来说,Apache Atlas是一款非常优秀的数据治理工具。它采用多种接地气的方法,比如实时更新元数据这招儿,还有提供那种一搜一个准、筛选功能强大到飞起的工具,再配上集成的机器学习黑科技,实实在在地让数据的准确度蹭蹭上涨,可用性也大大增强啦。
2023-04-17 16:08:35
1146
柳暗花明又一村-t
Tesseract
... BERT for Post-Processing Errors in OCR Output”,2020年“Journal of Digital Information Management”)。 因此,持续关注Tesseract及其相关领域的最新研究成果和技术动态,将有助于我们在实际项目中更好地应对OCR的各种挑战,不断提升自动化信息提取的效率和准确性。
2023-07-17 18:52:17
85
海阔天空
ElasticSearch
...avascript POST /my_index/_bulk { "index": { "_id": "1" } } {"title":"My first blog post","body":"Welcome to my blog!"} { "index": { "_id": "2" } } {"title":"My second blog post","body":"This is another blog post."} 在这个例子中,我们首先发送了一个index操作请求,它的_id参数是1。然后,我们发送了一条包含title和body字段的JSON数据。最后,咱们再接再厉,给那个index操作发了个请求,这次特意把_id参数设置成了2。就这样,我们一次性导入了两条数据。 三、搜索ElasticSearch中的数据 一旦我们将数据导入到了ElasticSearch中,就可以开始搜索数据了。在ElasticSearch里头找数据,那真是小菜一碟,你只需要给它发送一个search请求,轻轻松松就能搞定。下面的代码展示了如何搜索数据: javascript GET /my_index/_search { "query": { "match_all": {} } } 在这个例子中,我们发送了一个search操作请求,并指定了一个match_all查询。match_all查询表示匹配所有数据。所以,这条请求将会返回索引中的所有数据。 四、总结 通过上述步骤,我们可以很容易地将关系数据库中的数据导入到ElasticSearch中,并进行搜索。不过,这只是个入门级别的例子,真正实操起来,要考虑的因素可就多了去了,比如数据清洗这个环节,还有数据转换什么的,都是必不可少的步骤。所以,对那些琢磨着要把关系数据库里的数据挪到ElasticSearch的朋友们来说,这只是万里长征第一步。他们还需要投入更多的时间和精力,去深入学习、全面掌握ElasticSearch的各种知识和技术要点。
2023-06-25 20:52:37
456
梦幻星空-t
HTML
...程。通过编写特定的 post-build 脚本或利用 CI/CD 工具提供的钩子函数,可以在编译完成后执行诸如文件上传、环境部署等更多后处理任务,从而提升开发团队的工作效率和协作水平。 总的来说,Webpack 作为构建工具的角色已经超越了单纯的模块打包,而是在工程化实践与 DevOps 流程中发挥着愈发关键的作用。深入理解和熟练运用其各项功能,包括但不限于 watch 模式下的回调机制与插件扩展性,将有助于我们更好地应对各种实际开发场景,打造高效、稳定且灵活的前端工作流。
2023-12-07 22:55:37
690
月影清风_
Element-UI
...cript app.post('/api/submit-form', function(req, res) { const formData = req.body; // 在这里处理表单数据,可能包括数据库操作等 // ... res.send({ status: 'success', message: '表单提交成功' }); }); 五、实时反馈与优化 在实际应用中,用户可能会频繁提交表单或修改表单数据。为了让咱们的用户在使用产品时感觉更爽,我们可以加入一些实时反馈的东西,比如加载动画或者进度条啥的,这样他们就能看到自己的操作正在被处理,不会觉得系统卡顿或者慢吞吞的。另外,我们还要优化前端性能,就是说尽量减少那些没必要的请求,让页面加载得更快,操作起来更流畅。这样一来,用户体验绝对能提升一大截! html 提交 六、结语 通过上述步骤,我们不仅学会了如何在ElementUI中构建一个具有实时存储功能的表单应用,还了解了如何进行数据验证、错误处理以及优化用户体验。ElementUI,这货简直就是程序员们的超级助手啊!它那简洁高效的风格,就像是魔法一样,让开发者们轻轻松松就能打造出既实用又好看的应用程序。想象一下,你就像个魔法师,只需要几行代码,就能变出一个功能齐全、界面超赞的软件,是不是特别过瘾?ElementUI就是这么给力,让你的创意和想象力,都能在实际项目中大放异彩,不再受限于技术瓶颈。所以,如果你是个爱搞创新、追求极致体验的开发者,ElementUI绝对是你不可多得的好伙伴!哎呀,随着你慢慢摸清了Vue.js这个工具箱里的宝贝,你会发现能做的事儿多了去了!就像是解锁了新技能,可以玩转更复杂的网页设计,打造超级酷炫、功能强大的网站应用。想象一下,你就像个魔法师,手里的魔法棒(Vue.js)越用越熟练,能变出的东西就越来越厉害!是不是感觉整个人都充满了创造的激情?快来试试,让你的创意在网页上绽放吧!
2024-09-29 15:44:20
57
时光倒流
Superset
... requests.post("http://your-superset-server/api/v1/dashboard", json=payload) if response.status_code == 400: print("Invalid request, missing required parameters.") 解决方法是确保你的请求包含了所有必需的参数并且它们的数据类型和格式正确。 3.2 401 Unauthorized 当客户端尝试访问需要认证的资源而未提供有效凭据时,会出现此错误。在Superset中,这意味着我们需要带上有效的API密钥或其他认证信息。 python 正确示例:添加认证头 headers = {'Authorization': 'Bearer your-api-key'} response = requests.get("http://your-superset-server/api/v1/datasets", headers=headers) 3.3 403 Forbidden 即使你提供了认证信息,也可能由于权限不足导致403错误。这表示用户没有执行当前操作的权限。检查用户角色和权限设置,确保其有权执行所需操作。 3.4 404 Not Found 如上所述,当请求的资源在服务器上不存在时,将返回404错误。请确认你的API路径是否准确无误。 4. 总结与思考 在使用Superset API的过程中遭遇HTTP错误是常态而非例外。每一个错误码,其实都在悄悄告诉我们一个具体的小秘密,就是某个环节出了点小差错。这就需要我们在碰到问题时化身福尔摩斯,耐心细致地拨开层层迷雾,把问题的来龙去脉摸个一清二楚。每一个“啊哈!”时刻,就像是我们对技术的一次热情拥抱和深刻领悟,它不仅让咱们对编程的理解更上一层楼,更是我们在编程旅途中的宝贵财富和实实在在的成长印记。所以呢,甭管是捣鼓API调用出岔子了,还是在日常开发工作中摸爬滚打,咱们都得瞪大眼睛,保持一颗明察秋毫的心,还得有股子耐心去解决问题。让每一次失败的HTTP请求,都变成咱通往成功的垫脚石,一步一个脚印地向前走。
2023-06-03 18:22:41
67
百转千回
VUE
...录逻辑 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
灵动之光
Go Gin
...TP方法(GET, POST, PUT, DELETE): go v1.GET("/users", getUserList) v1.POST("/users", createUser) v1.PUT("/users/:id", updateUser) v1.DELETE("/users/:id", deleteUser) 这里,:id是一个动态参数,表示URL中的某个部分可以变化。比如说,当你访问"/api/v1/users/123"这个路径时,它就像个神奇的按钮,直接触发了“updateUser”这个函数的执行。 五、嵌套路由组 有时候,你可能需要更复杂的URL结构,这时可以使用嵌套路由组: go v1 := r.Group("/users") { v1.GET("/:id", getUser) v1.POST("", createUser) // 注意这里的空字符串,表示没有特定的路径部分 } 六、中间件的应用 在路由组上添加中间件可以为一组路由提供通用的功能,如验证、日志记录等。例如,我们可以在所有v1组的请求中添加身份验证中间件: go authMiddleware := func(c gin.Context) { // 这里是你的身份验证逻辑 } v1.Use(authMiddleware) 七、总结与拓展 通过以上步骤,你已经掌握了如何在Go Gin中使用路由组。路由组不仅帮助我们组织代码,还使我们能够更好地复用和扩展代码。当你碰到那些需要动点脑筋的难题,比如权限控制、出错应对的时候,你就把这玩意儿往深里挖,扩展升级,让它变得更聪明更顺溜。 记住,编程就像搭积木,每一块都对应着一个功能。用Go Gin的聪明路由功能,就像给你的代码设计了个贴心的导航系统,让结构井然有序,维护起来就像跟老朋友聊天一样顺溜。祝你在Go Gin的世界里玩得开心,构建出强大的Web应用!
2024-04-12 11:12:32
501
梦幻星空
NodeJS
...()或者app.post()方法就大功告成了。就像是给你的程序扩展新的“小径”一样,轻松便捷。 然后,我们来看一下如何使用Koa来创建一个新的web应用: javascript const Koa = require('koa'); const app = new Koa(); app.use(async ctx => { ctx.body = 'Hello World!'; }); app.listen(3000, () => { console.log('Server is listening at http://localhost:3000'); }); 这段代码也定义了一个简单的HTTP服务,但是使用了Koa的柯里化和async/await特性,使得代码更加简洁和易读。举个例子来说,这次咱们就做了件特简单的事儿,就是把返回的内容设成'Hello World!',别的啥路由规则啊,都没碰,没加。 七、结论 总的来说,Koa和Express都是非常优秀的Node.js web开发框架,它们各有各的优点和适用场景。无论是选择哪一种框架,都需要根据自己的需求和技术水平进行考虑。希望通过这篇文章,能够帮助大家更好地理解和掌握这两种框架,为自己的web开发工作带来更大的便利和效率。
2023-07-31 20:17:23
101
青春印记-t
NodeJS
...CSRF攻击 在处理POST、PUT等涉及用户数据变更的操作时,可以考虑集成csurf中间件以验证跨站点请求伪造(CSRF)令牌: bash $ npm install csurf javascript const csurf = require('csurf'); // 配置CSRF保护 const csrf = csurf(); app.use(csurf({ cookie: true })); // 将CSRF令牌存储到cookie中 // 处理登录API POST请求 app.post('/login', csrf(), (req, res) => { const { email, password, _csrfToken } = req.body; // 注意获取CSRF token if (validateCredentials(email, password)) { // 登录成功 } else { res.status(401).json({ error: 'Invalid credentials' }); } }); 四、总结与展望 在使用Express进行API开发时,确保安全性至关重要。通过合理的CSP、CORS策略、CSRF防护以及利用其他如JWT(Json Web Tokens)的身份验证方法,我们的API不仅能更好地服务于前端应用,还能有效地抵御各类常见的网络攻击,确保数据传输的安全性。 当然,随着业务的发展和技术的进步,我们会面临更多安全挑战和新的解决方案。Node.js和它身后的生态系统,最厉害的地方就是够灵活、够扩展。这就意味着,无论我们面对多复杂的场景,总能像哆啦A梦找百宝箱一样,轻松找到适合的工具和方法来应对。所以,对咱们这些API开发者来说,要想把Web服务做得既安全又牛逼,就得不断学习、紧跟技术潮流,时刻关注行业的新鲜动态。这样一来,咱就能打造出更棒、更靠谱的Web服务啦!
2024-02-13 10:50:50
79
烟雨江南-t
SpringBoot
... }; axios.post('/api/register', formData) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); }); } } 三、问题分析 1. 类型转换 首先,检查一下是不是类型转换的问题。SpringBoot在接收数据时,如果类型不匹配,可能会尝试将其转换为可接受的数据类型。比如说,假如你邮箱地址栏不小心输入了个纯数字“0”,当你想把它当成字符串来处理的时候,这家伙可能会调皮地变成一个空荡荡的啥都没有。 java // SpringBoot 部分 - 接收数据的Controller @PostMapping("/register") public ResponseEntity registerUser(@RequestBody Map formData) { String email = formData.get("email").toString(); // 如果email是数字0,这里会变成"" // ... } 2. 默认值 另一个可能的原因是,前端在发送数据前没有正确处理可能的空值或默认值。你知道吗,有时候在发邮件前,email这哥们儿可能还没人填,这时它就暂且是JavaScript里的那个神秘存在“undefined”。一到要变成JSON格式,它就自动变身为“null”,然后后端大哥看见了,贴心地给它换个零蛋。 3. 数据验证 SpringBoot的@RequestBody注解默认会对JSON数据进行有效性校验,如果数据不符合约定的格式,它可能被视作无效,从而转化为默认值。检查Model层是否定义了默认值规则。 java // Model层 public class User { private String email; // ...其他字段 @NotBlank(message = "Email cannot be blank") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } 四、解决策略 1. 前端校验 确保在发送数据之前对前端数据进行清理和验证,避免空值或非预期值被发送。 2. 明确数据类型 在Vue.js中,可以使用v-model.number或者v-bind:value配合计算属性,确保数据在发送前已转换为正确的类型。 3. 后端配置 SpringBoot可以配置Jackson或Gson等JSON库,设置@JsonInclude(JsonInclude.Include.NON_NULL)来忽略所有空值。 4. 异常处理 添加适当的异常处理,捕获可能的转换异常并提供有用的错误消息。 五、结论 解决这个问题的关键在于理解数据流的每个环节,从前端到后端,每一个可能的类型转换和验证步骤都需要仔细审查。你知道吗,有时候生活就像个惊喜包,比如说JavaScript那些隐藏的小秘密,但别急,咱们一步步找,那问题的源头准能被咱们揪出来!希望这篇文章能帮助你在遇到类似困境时,更好地定位和解决“0”问题,提升开发效率和用户体验。 --- 当然,实际的代码示例可能需要根据你的项目结构和配置进行调整,以上只是一个通用的指导框架。记住,遇到问题时,耐心地查阅文档,结合调试工具,往往能更快地找到答案。祝你在前端与后端的交互之旅中一帆风顺!
2024-04-13 10:41:58
82
柳暗花明又一村_
Go Iris
...义登录路由 app.Post("/login", jwtMiddleware.LoginHandler) // 使用JWT中间件保护路由 app.Use(jwtMiddleware.MiddlewareFunc()) // 启动服务 app.Listen(":8080") } 2.2 OAuth2:授权的守护者 OAuth2是一个授权框架,允许第三方应用获得有限的访问权限,而不需要提供用户名和密码。通过OAuth2,用户可以授予应用程序访问他们资源的权限,而无需共享他们的凭据。 代码示例:OAuth2客户端授权 go package main import ( "github.com/kataras/iris/v12" oauth2 "golang.org/x/oauth2" ) func main() { app := iris.New() // 配置OAuth2客户端 config := oauth2.Config{ ClientID: "your_client_id", ClientSecret: "your_client_secret", RedirectURL: "http://localhost:8080/callback", Endpoint: oauth2.Endpoint{ AuthURL: "https://accounts.google.com/o/oauth2/auth", TokenURL: "https://accounts.google.com/o/oauth2/token", }, Scopes: []string{"profile", "email"}, } // 登录路由 app.Get("/login", func(ctx iris.Context) { url := config.AuthCodeURL("state") ctx.Redirect(url) }) // 回调路由处理 app.Get("/callback", func(ctx iris.Context) { code := ctx.URLParam("code") token, err := config.Exchange(context.Background(), code) if err != nil { ctx.WriteString("Failed to exchange token: " + err.Error()) return } // 在这里处理token,例如保存到数据库或直接使用 }) app.Listen(":8080") } 3. 构建策略决策树 智能授权 现在,我们已经了解了JWT和OAuth2的基本概念及其在Iris框架中的应用。接下来,我们要聊聊怎么把这两样东西结合起来,搞出一棵基于策略的决策树,这样就能更聪明地做授权决定了。 3.1 策略决策树的概念 策略决策树是一种基于规则的系统,用于根据预定义的条件做出决策。在这个情况下,我们主要根据用户的JWT信息(比如他们的角色和权限)和OAuth2的授权状态来判断他们是否有权限访问某些特定的资源。换句话说,就是看看用户是不是有“资格”去看那些东西。 代码示例:基于JWT的角色授权 go package main import ( "github.com/kataras/iris/v12" jwt "github.com/appleboy/gin-jwt/v2" ) type MyCustomClaims struct { Role string json:"role" jwt.StandardClaims } func main() { app := iris.New() jwtMiddleware, _ := jwt.New(&jwt.GinJWTMiddleware{ Realm: "test zone", Key: []byte("secret key"), Timeout: time.Hour, MaxRefresh: time.Hour, IdentityKey: "id", IdentityHandler: func(c jwt.Manager, ctx iris.Context) (interface{}, error) { claims := jwt.ExtractClaims(ctx) role := claims["role"].(string) return &MyCustomClaims{Role: role}, nil }, }) // 保护需要特定角色才能访问的路由 app.Use(jwtMiddleware.MiddlewareFunc()) // 定义受保护的路由 app.Get("/admin", jwtMiddleware.AuthorizeRole("admin"), func(ctx iris.Context) { ctx.Writef("Welcome admin!") }) app.Listen(":8080") } 3.2 结合OAuth2与JWT的策略决策树 为了进一步增强安全性,我们可以将OAuth2的授权状态纳入策略决策树中。这意味着,不仅需要验证用户的JWT,还需要检查OAuth2授权的状态,以确保用户具有访问特定资源的权限。 代码示例:结合OAuth2与JWT的策略决策 go package main import ( "github.com/kataras/iris/v12" jwt "github.com/appleboy/gin-jwt/v2" "golang.org/x/oauth2" ) // 自定义的OAuth2授权检查函数 func checkOAuth2Authorization(token oauth2.Token) bool { // 这里可以根据实际情况添加更多的检查逻辑 return token.Valid() } func main() { app := iris.New() jwtMiddleware, _ := jwt.New(&jwt.GinJWTMiddleware{ Realm: "test zone", Key: []byte("secret key"), Timeout: time.Hour, MaxRefresh: time.Hour, IdentityKey: "id", IdentityHandler: func(c jwt.Manager, ctx iris.Context) (interface{}, error) { claims := jwt.ExtractClaims(ctx) role := claims["role"].(string) return &MyCustomClaims{Role: role}, nil }, }) app.Use(jwtMiddleware.MiddlewareFunc()) app.Get("/secure-resource", jwtMiddleware.AuthorizeRole("user"), func(ctx iris.Context) { // 获取当前请求的JWT令牌 token := jwtMiddleware.TokenFromRequest(ctx.Request()) // 检查OAuth2授权状态 if !checkOAuth2Authorization(token) { ctx.StatusCode(iris.StatusUnauthorized) ctx.Writef("Unauthorized access") return } ctx.Writef("Access granted to secure resource") }) app.Listen(":8080") } 4. 总结与展望 通过以上讨论和代码示例,我们看到了如何在Iris框架中有效地使用JWT和OAuth2来构建一个智能的授权决策系统。这不仅提高了应用的安全性,还增强了用户体验。以后啊,随着技术不断进步,咱们可以期待更多酷炫的新方法来简化这些流程,让认证和授权变得超级高效又方便。 希望这篇探索之旅对你有所帮助,也欢迎你加入讨论,分享你的见解和实践经验!
2024-11-07 15:57:06
56
夜色朦胧
Ruby
... |i| pool.post do sleep(1) puts "Task {i} completed" end end pool.shutdown pool.wait_for_termination 分析: 在这个例子中,线程池的大小被设置为2,但有20个任务需要执行。哎呀,这就好比你请了个帮手,但他一次只能干两件事,其他事儿就得排队等着,得等前面那两件事儿干完了,才能轮到下一件呢!这种情况下,整个程序的执行时间会显著延长。 解决方案: 为了优化线程池的性能,我们需要根据系统的负载情况动态调整线程池的大小。可以使用Concurrent::CachedThreadPool,它会根据当前的任务数量自动调整线程的数量。 修正后的代码: ruby 使用缓存线程池 require 'concurrent' pool = Concurrent::CachedThreadPool.new 20.times do |i| pool.post do sleep(1) puts "Task {i} completed" end end sleep(10) 给线程池足够的时间完成任务 pool.shutdown pool.wait_for_termination 总结: 线程池就像一把双刃剑,用得好可以提升效率,用不好则会成为负担。记住,线程池的大小要根据实际情况灵活调整。 --- 6. 示例四 忽略异常的代价 场景描述: 并发编程的一个常见问题是,线程中的异常不容易被察觉。如果你没有妥善处理这些异常,程序可能会因为一个小错误而崩溃。 问题出现: 假设你有一个线程在执行某个操作时抛出了异常,但你没有捕获它,那么整个线程池可能会因此停止工作。 代码示例: ruby 忽略异常的代码 threads = [] 5.times do |i| threads << Thread.new do raise "Error in thread {i}" if i == 2 puts "Thread {i} completed" end end threads.each(&:join) 分析: 在这个例子中,当i == 2时,线程会抛出一个异常。哎呀糟糕!因为我们没抓住这个异常,程序直接就挂掉了,别的线程啥的也别想再跑了。 解决方案: 为了防止这种情况发生,我们应该在每个线程中添加异常捕获机制。比如,可以用begin-rescue-end结构来捕获异常并进行处理。 修正后的代码: ruby 捕获异常的代码 threads = [] 5.times do |i| threads << Thread.new do begin raise "Error in thread {i}" if i == 2 puts "Thread {i} completed" rescue => e puts "Thread {i} encountered an error: {e.message}" end end end threads.each(&:join) 总结: 异常就像隐藏在暗处的敌人,稍不注意就会让你措手不及。学会捕获和处理异常,是成为一个优秀的并发编程者的关键。 --- 7. 结语 好了,今天的分享就到这里啦!并发编程确实是一项强大的技能,但也需要谨慎对待。大家看看今天这个例子,是不是觉得有点隐患啊?希望能引起大家的注意,也学着怎么避开这些坑,别踩雷了! 最后,我想说的是,编程是一门艺术,也是一场冒险。每次遇到新挑战,我都觉得像打开一个神秘的盲盒,既兴奋又紧张。不过呢,光有好奇心还不够,还得有点儿耐心,就像种花一样,得一点点浇水施肥,不能急着看结果。相信只要我们不断学习、不断反思,就一定能写出更加优雅、高效的代码! 祝大家编码愉快!
2025-04-25 16:14:17
32
凌波微步
转载文章
... requests.post(url=url, data=data, headers=headers, timeout=self.timeout)res = {"status_code": resp.status_code}try:res["data"] = json.loads(resp.text)return resexcept Exception as e:print(e)def make_idphoto(self, file_path, bk, spec="2"):"""证件照制作接口:param file_path::param bk::param spec::return:"""photo_base64 = self.get_photo_base64(file_path)body_json = {"photo": photo_base64,"bk": bk,"with_photo_key": 1,"spec": spec,"type": "jpg"}body = json.dumps(body_json)body_md5 = self.get_md5_data(body=body)self.headers.update({'Content-MD5': body_md5})data = self.aiseg_request(url=self.make_idphoto_url, data=body, headers=self.headers)return dataif __name__ == "__main__":file_path = "图片地址"idphoto = Idphoto(appcode="你的appcode")d = idphoto.make_idphoto(file_path, "red", "2")print(d) 3.3 实验结果与分析 原图片 背景为红色生成的证件照 背景为蓝色生成的证件照 另外尝试了使用柴犬照片做实验,也生成了证件照 原图 背景为红色生成的证件照 参考(可供参考的链接和引用文献) 1.参考:BiHand: Recovering Hand Mesh with Multi-stage Bisected Hourglass Networks(BMVC2020) 论文链接:https://arxiv.org/pdf/2008.05079.pdf 本篇文章为转载内容。原文链接:https://blog.csdn.net/m0_37758063/article/details/131128967。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-07-11 23:36:51
131
转载
转载文章
...删除相应内容。 介绍Postgres-XL Postgres-XL 全称为 Postgres eXtensible Lattice,是TransLattice公司及其收购数据库技术公司–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
转载
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
nl file.txt
- 给文件每一行添加行号。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"