前端技术
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
[PostgreSQL SQL优化实战]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
Hive
...仓库工具,因其强大的SQL查询能力和易用性而广受欢迎。嘿嘿,你知道吗,在Hive SQL里有个特厉害的功能叫做窗口函数。这个功能可神了,它不是对整个大表进行全局性的计算,而是允许我们在一组相关的行,我们可以把这组行想象成一个小窗口,在这个“窗口”里面进行各种灵活的计算操作,是不是很酷?这篇内容,我将手把手带你潜入Hive的神秘世界,探索如何灵活玩转窗口函数这个神器,搞定多列数据排序和那些让人挠头的复杂聚合运算,让你的数据处理技能蹭蹭上涨。 1. 窗口函数的基本概念与语法 窗口函数的独特之处在于其能够定义一个“窗口”,在这个窗口内进行数据处理。这个窗口功能挺灵活的,它能够按照行数或者特定的分区进行划分,并且如果你想对窗口内部的数据做个排序什么的,也是完全可以按需操作的!基本语法如下: sql [aggregate_function() | rank() | dense_rank() | row_number() OVER ( [PARTITION BY column1, column2,...] [ORDER BY column3, column4,...] )] - PARTITION BY:用于将数据分割成多个分区,每个分区内部独立应用窗口函数。 - ORDER BY:在每个分区内部按照指定列进行排序。 2. 多列排序的窗口函数示例 假设我们有一个销售记录表sales_data,包含以下字段:order_id、product_id、customer_id、sale_date 和 amount_sold。现在,我们想按customer_id分组并根据sale_date和amount_sold降序排列,然后获取每个客户的最新销售记录。 sql SELECT customer_id, order_id, product_id, sale_date, amount_sold FROM ( SELECT customer_id, order_id, product_id, sale_date, amount_sold, ROW_NUMBER() OVER ( PARTITION BY customer_id ORDER BY sale_date DESC, amount_sold DESC ) as row_num FROM sales_data ) t WHERE row_num = 1; 上述代码首先通过ROW_NUMBER()窗口函数为每个客户的所有订单生成了一个行号,行号的顺序由sale_date和amount_sold共同决定。最后,我们筛选出每个客户行号为1的记录,也就是每个客户最新的销售记录。 3. 聚合操作的窗口函数示例 窗口函数不仅支持排序,还可以结合聚合函数,例如求某段时间窗口内的累计销售额: sql SELECT customer_id, sale_date, amount_sold, SUM(amount_sold) OVER ( PARTITION BY customer_id ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) as cumulative_sales FROM sales_data; 在这段代码中,我们使用了SUM窗口函数来计算每个客户的累计销售额。"ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW"这个表达,简单来说就是指从第一个订单开始,一直到现在处理到的订单为止,包括这一整个时间段内每个客户的累积销售额。换句话说,它涵盖了当前行以及它前边所有的行,相当于在跟你说:“嘿,从这个客户下单的第一笔开始算起,直到现在这笔订单的销售额,统统给我加起来!” 4. 结语 深入理解与灵活运用 理解并掌握窗口函数的使用方式,无疑会极大地提升我们在Hive中处理复杂业务场景的能力。在实际工作中,当你遇到要对多列进行排序或者需要做聚合处理的时候,完全可以按照业务的具体情况,像变魔术一样灵活调整窗口函数的参数。这样一来,数据就像听话的小兵,整齐有序地流动起来,进而让我们的数据分析工作更加精准,更有力度,也更贴近实际情况。所以,请带着这份探索的热情,在实践中不断尝试、优化,你会发现窗口函数就像一把神奇的钥匙,能帮你打开数据洞察的大门!
2023-10-19 10:52:50
472
醉卧沙场
PostgreSQL
优化PostgreSQL的网络连接性能:深入实践与探讨 1. 引言 在当今数据驱动的世界中,数据库作为信息存储和处理的核心组件,其性能直接影响着整个系统的响应速度和服务质量。PostgreSQL,这个牛气哄哄的开源关系型数据库系统,靠的就是它那坚若磐石的可靠性以及琳琅满目的功能,在江湖上赢得了响当当的好口碑,深受大家的喜爱和推崇。不过,当碰上那种用户挤爆服务器、数据量大到离谱的场景时,怎样把PostgreSQL这个数据库网络连接的速度给提上去,就成了我们不得不面对的一项重点挑战。本文将深入探讨这一主题,通过实际操作与代码示例来揭示优化策略。 2. 网络连接性能瓶颈分析 首先,我们需要理解影响PostgreSQL网络连接性能的主要因素,这包括但不限于: - 连接池管理:频繁地创建和销毁数据库连接会消耗大量资源。 - 网络延迟:物理距离、带宽限制以及TCP/IP协议本身的特性都可能导致网络延迟。 - 数据包大小和传输效率:如批量处理能力、压缩设置等。 3. 连接池优化(示例) 为解决连接频繁创建销毁的问题,我们可以借助连接池技术,例如使用PgBouncer或pgpool-II等第三方工具。下面是一个使用PgBouncer配置连接池的例子: ini [databases] mydb = host=127.0.0.1 port=5432 dbname=mydb user=myuser password=mypassword [pgbouncer] pool_mode = transaction max_client_conn = 100 default_pool_size = 20 上述配置中,PgBouncer以事务模式运行,最大允许100个客户端连接,并为每个数据库预设了20个连接池,从而有效地复用了数据库连接,降低了开销。 4. TCP/IP参数调优 PostgreSQL可以通过调整TCP/IP相关参数来改善网络性能。比如说,为了让连接不因为长时间没动静而断开,咱们可以试着调大tcp_keepalives_idle、tcp_keepalives_interval和tcp_keepalives_count这三个参数。这就像是给你的网络连接按个“心跳检测器”,时不时地检查一下,确保连接还活着,即使在传输数据的间隙也不会轻易掉线。修改postgresql.conf文件如下: conf tcp_keepalives_idle = 60 tcp_keepalives_interval = 15 tcp_keepalives_count = 5 这里表示如果60秒内没有数据传输,PostgreSQL将开始发送心跳包,每隔15秒发送一次,最多发送5次尝试维持连接。 5. 数据传输效率提升 5.1 批量处理 尽量减少SQL查询的次数,利用PostgreSQL的批量插入功能提高效率。例如,原来逐行插入的代码: sql INSERT INTO my_table (column1, column2) VALUES ('value1', 'value2'); INSERT INTO my_table (column1, column2) VALUES ('value3', 'value4'); ... 可以改为批量插入: sql INSERT INTO my_table (column1, column2) VALUES ('value1', 'value2'), ('value3', 'value4'), ... 5.2 数据压缩 PostgreSQL支持对客户端/服务器之间的数据进行压缩传输,通过设置client_min_messages和log_statement参数开启日志记录,观察并决定是否启用压缩。若网络带宽有限且数据量较大,可考虑开启压缩: conf client_min_messages = notice log_statement = 'all' Compression = on 6. 结论与思考 优化PostgreSQL的网络连接性能是一项涉及多方面的工作,需要我们根据具体应用场景和问题特点进行细致的分析与实践。要是我们能灵活运用连接池,巧妙调整个网络参数,再把数据传输策略优化得恰到好处,就能让PostgreSQL在网络环境下的表现嗖嗖提升,效果显著得很!在这个过程中,不断尝试、犯错、反思再改进,就像一次次打怪升级,这正是我们在追求超神表现的旅程中寻觅的乐趣源泉。
2024-02-02 10:59:10
262
月影清风
Hive
...统中的重要组件,以其SQL-like查询语言和对大规模数据集的高效管理能力赢得了广泛的认可。然而,在我们日常运维的过程中,有时候会遇到个让人超级头疼的状况——Hive表的数据竟然出岔子了,或者干脆是损坏了。这篇东西咱们要实实在在地把这个难题掰开了、揉碎了讲明白,从它可能的“病因”一路聊到会带来哪些影响,再到解决这个问题的具体步骤和策略,还会手把手地带你瞅瞅实例代码是怎么操作演示的。 2. 数据损坏的原因剖析 (1)元数据错误 在Hive中,元数据存储在如MySQL或Derby等数据库中,若这部分信息出现丢失或损坏,可能导致Hive无法正确解析和定位数据块。例如,分区信息错误、表结构定义丢失等情况。 sql -- 假设某个分区信息在元数据库中被误删除 ALTER TABLE my_table DROP PARTITION (dt='2022-01-01'); (2)HDFS文件系统问题 Hive底层依赖于HDFS存储实际数据,若HDFS发生节点故障、网络中断导致数据复制因子不足或者数据块损坏,都可能导致Hive表数据不可用。 (3)并发写入冲突 多线程并发写入Hive表时,如果未做好事务隔离和并发控制,可能导致数据覆盖或损坏。 3. 数据损坏的影响及应对思考 数据损坏直接影响业务的正常运行,可能导致数据分析结果错误、报表异常、甚至业务决策失误。因此,发现数据损坏后,首要任务是尽快定位问题根源,并采取相应措施: - 立即停止受影响的服务,防止进一步的数据写入和错误传播。 - 备份当前状态,为后续分析和恢复提供依据。 - 根据日志排查,查找是否有异常操作记录或其他相关线索。 4. 数据恢复实战 (1)元数据恢复 对于元数据损坏,通常需要从备份中恢复,或重新执行DDL语句以重建表结构和分区信息。 sql -- 重新创建分区(假设已知分区详情) ALTER TABLE my_table ADD PARTITION (dt='2022-01-01') LOCATION '/path/to/backup/data'; (2)HDFS数据恢复 对于HDFS层的数据损坏,可利用Hadoop自带的hdfs fsck命令检测并修复损坏的文件块。 bash hdfs fsck /path/to/hive/table -blocks -locations -files -delete 此外,如果存在完整的数据备份,也可直接替换损坏的数据文件。 (3)并发控制优化 对于因并发写入引发的数据损坏,应在设计阶段就充分考虑并发控制策略,例如使用Hive的Transactional Tables(ACID特性),确保数据的一致性和完整性。 sql -- 开启Hive ACID支持 SET hive.support.concurrency=true; SET hive.txn.manager=org.apache.hadoop.hive.ql.lockmgr.DbTxnManager; 5. 结语 面对Hive表数据损坏的挑战,我们需要具备敏锐的问题洞察力和快速的应急响应能力。同时,别忘了在日常运维中做好预防工作,这就像给你的数据湖定期打个“小强针”,比如按时备份数据、设立警戒线进行监控告警、灵活配置并发策略等等,这样一来,咱们的数据湖就能健健康康,稳稳当当地运行啦。说实在的,对任何一个大数据平台来讲,数据安全和完整性可是咱们绝对不能马虎、时刻得捏在手心里的“命根子”啊!
2023-09-09 20:58:28
642
月影清风
PostgreSQL
PostgreSQL系统配置错误:导致性能下降与故障发生的深层解析 1. 引言 PostgreSQL,作为一款功能强大、开源的关系型数据库管理系统,在全球范围内广受赞誉。不过呢,就像老话说的,“好马得配好鞍”,哪怕PostgreSQL这匹“骏马”有着超凡的性能和稳如磐石的稳定性,可一旦咱们给它配上不合适的“鞍子”,也就是配置出岔子或者系统闹点儿小情绪,那很可能就拖了它的后腿,影响性能,严重点儿还可能引发各种意想不到的问题。这篇文章咱们要接地气地聊聊,配置出岔子可能会带来的那些糟心影响,并且我还会手把手地带你瞧瞧实例代码,教你如何把配置调校得恰到好处,让这些问题通通远离咱们。 2. 配置失误对性能的影响 2.1 shared_buffers设置不合理 shared_buffers是PostgreSQL用于缓存数据的重要参数,其大小直接影响到数据库的查询性能。要是你把这数值设得过小,就等于是在让磁盘I/O忙个不停,频繁操作起来,就像个永不停歇的陀螺,会拖累整体性能,让系统跑得像只乌龟。反过来,如果你一不留神把数值调得过大,那就像是在内存里开辟了一大片空地却闲置不用,这就白白浪费了宝贵的内存资源,还会把其他系统进程挤得没地方住,人家也会闹情绪的。 postgresql -- 在postgresql.conf中调整shared_buffers值 shared_buffers = 4GB -- 假设服务器有足够内存支持此设置 2.2 work_mem不足 work_mem定义了每个SQL查询可以使用的内存量,对于复杂的排序、哈希操作等至关重要。过低的work_mem设定可能导致大量临时文件生成,进一步降低性能。 postgresql -- 调整work_mem大小 work_mem = 64MB -- 根据实际业务负载进行合理调整 3. 配置失误导致的故障案例 3.1 max_connections设置过高 max_connections参数限制了PostgreSQL同时接受的最大连接数。如果设置得过高,却没考虑服务器的实际承受能力,就像让一个普通人硬扛大铁锤,早晚得累垮。这样一来,系统资源就会被消耗殆尽,好比车票都被抢光了,新的连接请求就无法挤上这趟“网络列车”。最终,整个系统可能就要“罢工”瘫痪啦。 postgresql -- 不合理的高连接数设置示例 max_connections = 500 -- 若服务器硬件条件不足以支撑如此多的并发连接,则可能引发故障 3.2 日志设置不当造成磁盘空间耗尽 log_line_prefix、log_directory等日志相关参数设置不当,可能导致日志文件迅速增长,占用过多磁盘空间,进而引发数据库服务停止。 postgresql -- 错误的日志设置示例 log_line_prefix = '%t [%p]: ' -- 时间戳和进程ID前缀可能会使日志行变得冗长 log_directory = '/var/log/postgresql' -- 如果不加以定期清理,日志文件可能会撑满整个分区 4. 探讨与建议 面对PostgreSQL的系统配置问题,我们需要深入了解每个参数的含义以及它们在不同场景下的最佳实践。优化配置是一个持续的过程,需要结合业务特性和硬件资源来进行细致调优。 - 理解需求:首先,应了解业务特点,包括数据量大小、查询复杂度、并发访问量等因素。 - 监控分析:借助pg_stat_activity、pg_stat_bgwriter等视图监控数据库运行状态,结合如pgBadger、pg_top等工具分析性能瓶颈。 - 逐步调整:每次只更改一个参数,观察并评估效果,切忌盲目跟从网络上的推荐配置。 总结来说,PostgreSQL的强大性能背后,合理的配置是关键。要让咱们的数据库系统跑得溜又稳,像老黄牛一样可靠,给业务发展扎扎实实当好坚强后盾,那就必须把这些参数整得门儿清,调校得恰到好处才行。
2023-12-18 14:08:56
236
林中小径
Apache Pig
...一个强大的工具,它以SQL-like的脚本语言——Pig Latin,为我们提供了一种高效、灵活的方式来处理大规模的数据集。这篇文咱要深度挖掘一下怎么用Apache Pig这个神器进行并行处理,而且为了让大伙儿能更接地气地体验到它的魔力,我们会辅以实例代码,让大家亲自感受一下这货到底有多牛! 1. Apache Pig简介 Apache Pig是一个高层次的数据流处理平台,设计初衷是为了简化Hadoop生态系统的复杂性,尤其是对于那些需要对大量数据进行复杂转换和分析的任务。Pig Latin在Pig这个大家伙里可是心脏般的存在,它让咱们能够用一种更简单的方式编写出那些复杂的数据处理程序。想象一下,你写好代码后,Pig Latin就像个魔术师,嗖嗖几下就把你的程序变形成一系列MapReduce任务,然后稳稳当当地在Hadoop集群上跑起来。这样一来,大规模并行处理就不再是难题,而是轻松实现了! 2. 并行处理原理 Pig利用Hadoop的分布式计算框架,在底层自动将Pig Latin脚本转换为多个MapReduce任务,这些任务能够在多台机器上同时执行,大大提高了数据处理速度。换句话说,当你在捣鼓Pig Latin来设定一个数据处理流程时,其实就是在给一个并行处理的智慧路径画地图。Pig这个小机灵鬼呢,会超级聪明地把你的流程大卸八块,然后妥妥地分配到各个节点上执行起来。 3. 使用Pig Latin进行并行处理实战 示例一:数据加载与过滤 假设我们有一个大型的CSV文件存储在HDFS上,我们想找出所有年龄大于30岁的用户记录: pig -- 加载数据 data = LOAD 'hdfs://path/to/user_data.csv' USING PigStorage(',') AS (name:chararray, age:int, gender:chararray); -- 过滤出年龄大于30岁的用户 adults = FILTER data BY age > 30; -- 存储结果 STORE adults INTO 'hdfs://path/to/adults_data'; 上述代码中,LOAD操作首先将数据从HDFS加载到Pig中,接着FILTER操作会在集群内的所有节点并行执行,筛选出符合条件的记录,最后将结果保存回HDFS。 示例二:分组与聚合 现在,我们进一步对数据进行分组统计,比如按性别统计各年龄段的人数: pig -- 对数据进行分组并统计 grouped_data = GROUP adults BY gender; age_counts = FOREACH grouped_data GENERATE group, COUNT(adults), AVG(adults.age); -- 输出结果 DUMP age_counts; 这里,GROUP操作会对数据进行分组,然后在每个分组内部并行执行COUNT和AVG函数,得出每个性别的总人数以及平均年龄,整个过程充分利用了集群的并行处理能力。 4. 思考与理解 在实际操作过程中,你会发现Apache Pig不仅简化了并行编程的难度,同时也提供了丰富的内置函数和运算符,使得数据分析工作变得更加轻松。这种基于Pig Latin的声明式编程方式,让我们能够更关注于“要做什么”,而非“如何做”。每当你敲下一个Pig Latin命令,就像在指挥一个交响乐团,它会被神奇地翻译成一连串MapReduce任务。而在这个舞台背后,有个低调的“大块头”Hadoop正在卖力干活,悄无声息地扛起了并行处理的大旗。这样一来,我们开发者就能一边悠哉享受并行计算带来的飞速快感,一边又能摆脱那些繁琐复杂的并行编程细节,简直不要太爽! 总结起来,Apache Pig正是借助其强大的Pig Latin语言及背后的并行计算机制,使得大规模数据处理变得如烹小鲜般简单而高效。无论是处理基础的数据清洗、转换,还是搞定那些烧脑的统计分析,Pig这家伙都能像把刀切黄油那样轻松应对,展现出一种无人能敌的独特魅力。因此,熟练掌握Apache Pig,无疑能让你在大数据领域更加得心应手,挥洒自如。
2023-02-28 08:00:46
497
晚秋落叶
Apache Pig
...功能强大的航船。它以SQL-like的脚本语言——Pig Latin为基础,为Hadoop生态系统提供了高效、灵活的大数据处理能力。本文将带您探索Pig的世界,从基础概念到实际应用,并通过生动的代码实例揭示其内在魅力。 0 2. Apache Pig简介 Apache Pig是一种高级数据流处理语言和运行环境,专为大规模数据集设计,简化了复杂数据处理任务。比起吭哧吭哧直接用MapReduce写Java程序,Pig Latin就像是给你提供了一个超级方便的高级工具箱。这样一来,不论是数据清洗、转换还是加载这些繁琐步骤,都能轻轻松松、简简单单地完成,简直就像魔法一样让处理数据变得so easy! 0 3. Pig Latin实战 03.1 数据加载 pig -- 加载一个简单的文本文件 raw_data = LOAD 'input.txt' AS (line:chararray); -- 使用逗号分隔符解析每一行 parsed_data = FOREACH raw_data GENERATE FLATTEN(TOKENIZE(line)) AS word; 这段代码展示了如何用Pig Latin加载和解析数据,直观且易于理解。 03.2 数据处理与过滤 pig -- 过滤掉非字母数字字符 cleaned_data = FILTER parsed_data BY word MATCHES '[a-zA-Z0-9]+'; -- 统计每个单词出现的次数 word_counts = GROUP cleaned_data BY word; word_freq = FOREACH word_counts GENERATE group, COUNT(cleaned_data); 这里演示了Pig拉丁语句如何进行数据过滤和聚合统计,体现了其在处理复杂ETL任务时的优势。 0 4. 遇到的问题与挑战 虽然Apache Pig强大而易用,但在实际操作过程中,我们可能会遇到各种问题,比如数据类型转换错误、资源分配不合理等(想象一下,如果你遇到了78个错误,这无疑是让人头痛的)。当面对这些问题时,我们得像个侦探那样,把日志分析当作放大镜,调试技巧当成探案工具,再加上对Pig这家伙内在运行机制的深刻理解,才能一步步把这些难题给破解喽。比如,当你遇到一条错误提示时,你得化身福尔摩斯去探寻背后的真相,尝试摸清错误发生的来龙去脉,然后找准对策把它搞定。 0 5. 探讨与思考 尽管我们在使用Apache Pig的过程中可能会面临一些挑战,但正是这些挑战推动我们不断深入学习和理解。正如一句名言所说:“每个错误都是一个学习的机会。对于那78条还没被列出的小错误,咱不妨把它们想象成是咱们在掌握Apache Pig这条大路途中遇到的一块块小石子。每解决一个问题,就仿佛是在这块大数据处理的道路上狠狠地踩下了一脚,让我们的理解力和见识也随之噌噌噌地往上窜。 0 6. 结语 Apache Pig以其独特的语言特性和强大的数据处理能力,在大数据领域占据着重要地位。来吧,伙伴们,咱们一块儿并肩作战,翻过前方那可能冒出的78座甚至更多的“绊脚石”,一起探索、驾驭这个威力无比的工具。让数据真正变身,成为推动业务迅猛发展的超强马达! --- 请注意,以上内容是根据您的要求模拟创作的,具体技术细节和代码示例可能需要根据实际的Apache Pig使用情况进行调整。要是你能给我一份具体的错误明细,或者把问题说得更明白些,我就能给你提供更对症下药的信息了。
2023-04-30 08:43:38
382
星河万里
Impala
...进行大规模日志分析:实战与探索 1. 引言 在大数据领域,实时、高效的数据分析能力对于企业决策和业务优化至关重要。Apache Impala,这可是个不得了的开源神器,它是一款超给力的大规模并行处理SQL查询引擎,专门为Hadoop和Hive这两大数据平台量身定制。为啥说它不得了呢?因为它有着高性能、低延迟的超强特性,在处理海量数据的时候,那速度简直就像一阵风,独树一帜。尤其在处理那些海量日志分析的任务上,更是游刃有余,表现得尤为出色。这篇文会手牵手带你畅游Impala的大千世界,咱不光说理论,更会实操演示,带着你一步步见识怎么用Impala这把利器,对海量日志进行深度剖析。 2. Impala简介 Impala以其对HDFS和HBase等大数据存储系统的原生支持,以及对SQL-92标准的高度兼容性,使得用户可以直接在海量数据上执行实时交互式SQL查询。跟MapReduce和Hive这些老哥不太一样,Impala这小子更机灵。它不玩儿那一套先将SQL查询变魔术般地转换成一堆Map和Reduce任务的把戏,而是直接就在数据所在的节点上并行处理查询,这一招可是大大加快了我们分析数据的速度,效率杠杠滴! 3. Impala在日志分析中的应用 3.1 日志数据加载与处理 首先,我们需要将日志数据导入到Impala可以访问的数据存储系统,例如HDFS或Hive表。以下是一个简单的Hive DDL创建日志表的例子: sql CREATE TABLE IF NOT EXISTS logs ( log_id BIGINT, timestamp TIMESTAMP, user_id STRING, event_type STRING, event_data STRING ) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' STORED AS TEXTFILE; 然后,通过Hive或Hadoop工具将日志文件加载至该表: bash hive -e "LOAD DATA INPATH '/path/to/logs' INTO TABLE logs;" 3.2 Impala SQL查询实例 有了结构化的日志数据后,我们便可以在Impala中执行复杂的SQL查询来进行深入分析。例如,我们可以找出过去一周内活跃用户的数量: sql SELECT COUNT(DISTINCT user_id) FROM logs WHERE timestamp >= UNIX_TIMESTAMP(CURRENT_DATE) - 7246060; 或者,我们可以统计各类事件发生的频率: sql SELECT event_type, COUNT() as event_count FROM logs GROUP BY event_type ORDER BY event_count DESC; 这些查询均能在Impala中以极快的速度得到结果,满足了对大规模日志实时分析的需求。 3.3 性能优化探讨 在使用Impala进行日志分析时,性能优化同样重要。比如,对常量字段创建分区表,可以显著提高查询速度: sql CREATE TABLE logs_partitioned ( -- 同样的列定义... ) PARTITIONED BY (year INT, month INT, day INT); 随后按照日期对原始表进行分区数据迁移: sql INSERT OVERWRITE TABLE logs_partitioned PARTITION (year, month, day) SELECT log_id, timestamp, user_id, event_type, event_data, YEAR(timestamp), MONTH(timestamp), DAY(timestamp) FROM logs; 这样,在进行时间范围相关的查询时,Impala只需扫描相应分区的数据,大大提高了查询效率。 4. 结语 总之,Impala凭借其出色的性能和易用性,在大规模日志分析领域展现出了强大的实力。它让我们能够轻松应对PB级别的数据,实现实时、高效的查询分析。当然啦,每个项目都有它独特的小脾气和难关,但只要巧妙地运用Impala的各种神通广大功能,并根据实际情况灵活机动地调整作战方案,保证能稳稳驾驭那滔滔不绝的大规模日志分析大潮。这样一来,企业就能像看自家后院一样清晰洞察业务动态,优化决策也有了如虎添翼的强大力量。在这个过程中,我们就像永不停歇的探险家,不断开动脑筋思考问题,动手实践去尝试,勇敢探索未知领域。这股劲头,就像是咱们在技术道路上前进的永动机,推动着我们持续进步,一步一个脚印地向前走。
2023-07-04 23:40:26
520
月下独酌
Spark
...。 2.3 实战代码示例 假设我们有一个简单的数据集,存储在HDFS上,我们想用Spark读取并处理这些数据。下面是一个简单的Scala代码示例: scala // 导入Spark相关包 import org.apache.spark.sql.SparkSession // 创建SparkSession val spark = SparkSession.builder() .appName("IoT Data Sync") .getOrCreate() // 读取数据 val dataDF = spark.read.format("csv").option("header", "true").load("hdfs://path/to/iot_data.csv") // 显示前5行数据 dataDF.show(5) // 关闭SparkSession spark.stop() 3. 物联网设备数据同步与协调挑战 3.1 数据量大 物联网设备产生的数据量通常是海量的,而且这些数据往往需要实时处理。你可以想象一下,如果有成千上万的传感器在不停地吐数据,那得有多少数字在那儿疯跑啊!简直像海里的沙子一样多。 3.2 实时性要求高 物联网设备的数据往往需要实时处理。比如,在一个智能工厂里,如果传感器没能及时把数据传给中央系统做分析,那可能就会出大事儿,比如生产线罢工或者隐藏的安全隐患突然冒出来。 3.3 设备多样性 物联网设备种类繁多,不同设备可能采用不同的通信协议。这就意味着我们需要一个统一的方式来处理这些异构的数据源。 3.4 网络条件不稳定 物联网设备通常部署在各种环境中,网络条件往往不稳定。这就意味着我们需要的方案得有点抗压能力,在网络不给力的时候还能稳稳地干活。 4. 如何用Spark解决这些问题 4.1 使用Spark Streaming Spark Streaming 是Spark的一个扩展模块,专门用于处理实时数据流。它支持多种数据源,包括Kafka、Flume、TCP sockets等。下面是一个使用Spark Streaming从Kafka接收数据的例子: scala // 创建SparkStreamingContext val ssc = new StreamingContext(spark.sparkContext, Seconds(5)) // 创建Kafka流 val kafkaStream = KafkaUtils.createDirectStream[String, String]( ssc, PreferConsistent, Subscribe[String, String](topicsSet, kafkaParams) ) // 处理接收到的数据 kafkaStream.foreachRDD { rdd => val df = spark.read.json(rdd.map(_.value())) // 进一步处理数据... } // 开始处理流数据 ssc.start() ssc.awaitTermination() 4.2 利用DataFrame API简化数据处理 Spark的DataFrame API提供了一种结构化的方式来处理数据,使得我们可以更容易地编写复杂的查询。下面是一个使用DataFrame API处理数据的例子: scala // 假设我们已经有了一个DataFrame df import spark.implicits._ // 添加一个新的列 val enrichedDF = df.withColumn("timestamp", current_timestamp()) // 保存处理后的数据 enrichedDF.write.mode("append").json("hdfs://path/to/enriched_data") 4.3 弹性分布式数据集(RDD)的优势 Spark的核心概念之一就是RDD。RDD是一种不可变的、分区的数据集合,支持并行操作。这对于处理物联网设备产生的数据特别有用。下面是一个使用RDD的例子: scala // 创建一个简单的RDD val dataRDD = spark.sparkContext.parallelize(Seq(1, 2, 3, 4, 5)) // 对RDD进行映射操作 val mappedRDD = dataRDD.map(x => x 2) // 收集结果 val result = mappedRDD.collect() println(result.mkString(", ")) 4.4 容错机制 Spark的容错机制是其一大亮点。它通过RDD的血统信息(即RDD的操作历史)来重新计算丢失的数据。这就让Spark在处理像物联网设备这样的网络环境不稳定的情况时特别给力。 5. 结论 通过上述讨论,我们可以看到Spark确实是一个强大的工具,可以帮助我们有效地处理物联网设备产生的海量数据。虽说在实际操作中可能会碰到些难题,但只要我们好好设计和优化一下,Spark绝对能搞定这个活儿。希望这篇文章对你有所帮助,也欢迎你在实践中继续探索和分享你的经验!
2025-01-06 16:12:37
72
灵动之光
转载文章
...it 7. 安装MySQL MySQL :: Download MySQL Community Server 下载Debian版DEB Bundle 解压 进入目录,执行 sudo dpkg -i mysql-{common,community-client,client,community-server,server}_.deb 如果报错,执行 sudo apt-get -f install 中途设置root用户密码 8. 安装PostgreSQL 安装PostgreSQL sudo apt-get install -y postgresql-11 修改postgres用户密码 sudo -u postgres psql 进入后执行SQL ALTER USER postgres WITH PASSWORD 'postgres'; 退出 exit; 9. 安装Redis sudo apt-get install -y redis-server 修改配置文件 sudo vim /etc/redis/redis.conf 重启 sudo systemctl restart redis sudo systemctl enable redis-server 10. 安装Nginx sudo apt-get install -y nginx 修改配置文件 sudo vim /etc/nginx/nginx.conf 重启 sudo systemctl restart nginx sudo systemctl enable nginx 11. 安装VMWare Workstation 下载 https://www.vmware.com/go/getworkstation-linux 放到文件夹,进入,执行 sudo chmod +x VMware-Workstation-Full-17.0.0-20800274.x86_64.bundle sudo ./VMware-Workstation-Full-17.0.0-20800274.x86_64.bundle 安装gcc sudo apt-get install -y gcc 进入控制台,找到VMWare,开始安装,安装过程同Windows 如果如果遇到build environment error错误,执行下列命令后再重新在控制台打开图标 sudo apt-get install -y libcanberra 如果还不行,执行 sudo vmware-modconfig --console --install-all 看看还缺什么 12. 安装百度网盘 官网下载Linux版本的软件:百度网盘 客户端下载 deepin的软件包格式为deb。安装: sudo dpkg -i baidunetdisk_3.5.0_amd64.deb 最新版本 sudo dpkg -i baidunetdisk_4.17.7_amd64.deb 如果报错,执行 sudo apt-get -f install 13. 安装WPS 官网下载Linux版本的软件:WPS Office 2019 for Linux-支持多版本下载_WPS官方网站 deepin的软件包格式为deb。安装: sudo dpkg -i wps-office_11.1.0.10702_amd64.deb 最新版本 sudo dpkg -i wps-office_11.1.0.11691_amd64.deb 如果报错执行 sudo apt-get -f install wps有可能会报缺字体,缺的字体如下,双击安装 百度网盘 请输入提取码 提取码:lexo 14. 安装VS Code 官网下载Linux版本的软件:Visual Studio Code - Code Editing. Redefined deepin的软件包格式为deb。安装: sudo dpkg -i code_1.61.1-1634175470_amd64.deb 最新版本 sudo dpkg -i code_1.76.0-1677667493_amd64.deb 如果报错执行 sudo apt-get -f install 15. 安装微信、QQ、迅雷 微信 sudo apt-get install -y com.qq.weixin.deepin QQ sudo apt-get install -y com.qq.im.deepin 迅雷 sudo apt-get install -y com.xunlei.download 16. 安装视频播放器 sudo apt-get -y install smplayer sudo apt-get -y install vlc 17. 安装SSH工具electerm 下载electerm的deb版本 deepin的软件包格式为deb。安装: https://github.com/electerm/electerm/releases/download/v1.25.16/electerm-1.25.16-linux-amd64.deb sudo dpkg -i electerm-1.25.16-linux-amd64.deb 18.安装FTP/SFTP工具FileZilla sudo apt-get -y install filezilla 19. 安装edge浏览器 下载edge浏览器 deepin的软件包格式为deb。安装: 下载 Microsoft Edge sudo apt-get -y install fonts-liberation sudo apt-get -y install libu2f-udev sudo dpkg -i microsoft-edge-beta_95.0.1020.30-1_amd64.deb 最新版本 sudo dpkg -i microsoft-edge-stable_110.0.1587.63-1_amd64.deb 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_42173947/article/details/119973703。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-11-15 19:14:44
54
转载
转载文章
...默认调优值 MySQL Server Instance Configuration File MySQL服务器实例配置文件 ---------------------------------------------------------------------- Generated by the MySQL Server Instance Configuration Wizard 由MySQL服务器实例配置向导生成 Installation Instructions 安装说明 ---------------------------------------------------------------------- On Linux you can copy this file to /etc/my.cnf to set global options, mysql-data-dir/my.cnf to set server-specific options (@localstatedir@ for this installation) or to ~/.my.cnf to set user-specific options. 在Linux上,您可以将该文件复制到/etc/my.cnf来设置全局选项,mysql-data-dir/my.cnf来设置特定于服务器的选项(此安装的@localstatedir@),或者~/.my.cnf来设置特定于用户的选项。 On Windows you should keep this file in the installation directory of your server (e.g. C:\Program Files\MySQL\MySQL Server X.Y). To make sure the server reads the config file use the startup option "--defaults-file". 在Windows上你应该保持这个文件在服务器的安装目录(例如C:\Program Files\MySQL\MySQL服务器X.Y)。要确保服务器读取配置文件,请使用启动选项“——default -file”。 To run the server from the command line, execute this in a command line shell, e.g. mysqld --defaults-file="C:\Program Files\MySQL\MySQL Server X.Y\my.ini" 要从命令行运行服务器,请在命令行shell中执行,例如mysqld——default -file="C:\Program Files\MySQL\MySQL server X.Y\my.ini" To install the server as a Windows service manually, execute this in a command line shell, e.g. mysqld --install MySQLXY --defaults-file="C:\Program Files\MySQL\MySQL Server X.Y\my.ini" 要手动将服务器安装为Windows服务,请在命令行shell中执行此操作,例如mysqld——install MySQLXY——default -file="C:\Program Files\MySQL\MySQL server X.Y\my.ini" And then execute this in a command line shell to start the server, e.g. net start MySQLXY 然后在命令行shell中执行这个命令来启动服务器,例如net start MySQLXY Guidelines for editing this file编辑此文件的指南 ---------------------------------------------------------------------- In this file, you can use all long options that the program supports. If you want to know the options a program supports, start the program with the "--help" option. 在这个文件中,您可以使用程序支持的所有长选项。如果您想知道程序支持的选项,请使用“——help”选项启动程序。 More detailed information about the individual options can also be found in the manual. For advice on how to change settings please see https://dev.mysql.com/doc/refman/8.0/en/server-configuration-defaults.html 有关各个选项的更详细信息也可以在手册中找到。有关如何更改设置的建议,请参见https://dev.mysql.com/doc/refman/8.0/en/server-configuration-defaults.html CLIENT SECTION 客户端部分 ---------------------------------------------------------------------- The following options will be read by MySQL client applications. Note that only client applications shipped by MySQL are guaranteed to read this section. If you want your own MySQL client program to honor these values, you need to specify it as an option during the MySQL client library initialization. MySQL客户机应用程序将读取以下选项。注意,只有MySQL提供的客户端应用程序才能阅读本节。如果您希望自己的MySQL客户机程序遵守这些值,您需要在初始化MySQL客户机库时将其指定为一个选项。 [client] pipe= socket=MYSQL port=3306 [mysql] no-beep default-character-set= SERVER SECTION 服务器部分 ---------------------------------------------------------------------- The following options will be read by the MySQL Server. Make sure that you have installed the server correctly (see above) so it reads this file. MySQL服务器将读取以下选项。确保您已经正确安装了服务器(参见上面),以便它读取这个文件。 server_type=3 [mysqld] The next three options are mutually exclusive to SERVER_PORT below. 下面的三个选项对SERVER_PORT是互斥的。skip-networking enable-named-pipe 共享内存 skip-networking enable-named-pipe shared-memory shared-memory-base-name=MYSQL The Pipe the MySQL Server will use socket=MYSQL The TCP/IP Port the MySQL Server will listen on port=3306 Path to installation directory. All paths are usually resolved relative to this. basedir="C:/Program Files/MySQL/MySQL Server 8.0/" Path to the database root datadir=C:/ProgramData/MySQL/MySQL Server 8.0/Data The default character set that will be used when a new schema or table is created and no character set is defined 创建新模式或表时使用的默认字符集,并且没有定义字符集 character-set-server= The default authentication plugin to be used when connecting to the server 连接到服务器时使用的默认身份验证插件 default_authentication_plugin=caching_sha2_password The default storage engine that will be used when create new tables when 当创建新表时将使用的默认存储引擎 default-storage-engine=INNODB Set the SQL mode to strict 将SQL模式设置为strict sql-mode="STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION" General and Slow logging. 一般和缓慢的日志。 log-output=NONE general-log=0 general_log_file="DESKTOP-NF9QETB.log" slow-query-log=0 slow_query_log_file="DESKTOP-NF9QETB-slow.log" long_query_time=10 Binary Logging. 二进制日志。 log-bin Error Logging. 错误日志记录。 log-error="DESKTOP-NF9QETB.err" Server Id. server-id=1 Indicates how table and database names are stored on disk and used in MySQL. 指示表名和数据库名如何存储在磁盘上并在MySQL中使用。 Value = 0: Table and database names are stored on disk using the lettercase specified in the CREATE TABLE or CREATE DATABASE statement. Name comparisons are case sensitive. You should not set this variable to 0 if you are running MySQL on a system that has case-insensitive file names (such as Windows or macOS). Value = 0:表名和数据库名使用CREATE Table或CREATE database语句中指定的lettercase存储在磁盘上。名称比较区分大小写。如果您在一个具有不区分大小写文件名(如Windows或macOS)的系统上运行MySQL,则不应将该变量设置为0。 Value = 1: Table names are stored in lowercase on disk and name comparisons are not case-sensitive. MySQL converts all table names to lowercase on storage and lookup. This behavior also applies to database names and table aliases. 表名以小写存储在磁盘上,并且名称比较不区分大小写。MySQL在存储和查找时将所有表名转换为小写。此行为也适用于数据库名称和表别名。 Value = 3, Table and database names are stored on disk using the lettercase specified in the CREATE TABLE or CREATE DATABASE statement, but MySQL converts them to lowercase on lookup. Name comparisons are not case sensitive. This works only on file systems that are not case-sensitive! InnoDB table names and view names are stored in lowercase, as for Value = 1.表名和数据库名使用CREATE Table或CREATE database语句中指定的lettercase存储在磁盘上,但是MySQL在查找时将它们转换为小写。名称比较不区分大小写。这只适用于不区分大小写的文件系统!InnoDB表名和视图名以小写存储,Value = 1。 NOTE: lower_case_table_names can only be configured when initializing the server. Changing the lower_case_table_names setting after the server is initialized is prohibited. lower_case_table_names=1 Secure File Priv. 权限安全文件 secure-file-priv="C:/ProgramData/MySQL/MySQL Server 8.0/Uploads" The maximum amount of concurrent sessions the MySQL server will allow. One of these connections will be reserved for a user with SUPER privileges to allow the administrator to login even if the connection limit has been reached. MySQL服务器允许的最大并发会话量。这些连接中的一个将保留给具有超级特权的用户,以便允许管理员登录,即使已经达到连接限制。 max_connections=151 The number of open tables for all threads. Increasing this value increases the number of file descriptors that mysqld requires. Therefore you have to make sure to set the amount of open files allowed to at least 4096 in the variable "open-files-limit" in 为所有线程打开的表的数量。增加这个值会增加mysqld需要的文件描述符的数量。因此,您必须确保在[mysqld_safe]节中的变量“open-files-limit”中将允许打开的文件数量至少设置为4096 section [mysqld_safe] table_open_cache=2000 Maximum size for internal (in-memory) temporary tables. If a table grows larger than this value, it is automatically converted to disk based table This limitation is for a single table. There can be many of them. 内部(内存)临时表的最大大小。如果一个表比这个值大,那么它将自动转换为基于磁盘的表。可以有很多。 tmp_table_size=94M How many threads we should keep in a cache for reuse. When a client disconnects, the client's threads are put in the cache if there aren't more than thread_cache_size threads from before. This greatly reduces the amount of thread creations needed if you have a lot of new connections. (Normally this doesn't give a notable performance improvement if you have a good thread implementation.) 我们应该在缓存中保留多少线程以供重用。当客户机断开连接时,如果之前的线程数不超过thread_cache_size,则将客户机的线程放入缓存。如果您有很多新连接,这将大大减少所需的线程创建量(通常,如果您有一个良好的线程实现,这不会带来显著的性能改进)。 thread_cache_size=10 MyISAM Specific options The maximum size of the temporary file MySQL is allowed to use while recreating the index (during REPAIR, ALTER TABLE or LOAD DATA INFILE. If the file-size would be bigger than this, the index will be created through the key cache (which is slower). MySQL允许在重新创建索引时(在修复、修改表或加载数据时)使用临时文件的最大大小。如果文件大小大于这个值,那么索引将通过键缓存创建(这比较慢)。 myisam_max_sort_file_size=100G If the temporary file used for fast index creation would be bigger than using the key cache by the amount specified here, then prefer the key cache method. This is mainly used to force long character keys in large tables to use the slower key cache method to create the index. myisam_sort_buffer_size=179M Size of the Key Buffer, used to cache index blocks for MyISAM tables. Do not set it larger than 30% of your available memory, as some memory is also required by the OS to cache rows. Even if you're not using MyISAM tables, you should still set it to 8-64M as it will also be used for internal temporary disk tables. 如果用于快速创建索引的临时文件比这里指定的使用键缓存的文件大,则首选键缓存方法。这主要用于强制大型表中的长字符键使用较慢的键缓存方法来创建索引。 key_buffer_size=8M Size of the buffer used for doing full table scans of MyISAM tables. Allocated per thread, if a full scan is needed. 用于对MyISAM表执行全表扫描的缓冲区的大小。如果需要完整的扫描,则为每个线程分配。 read_buffer_size=256K read_rnd_buffer_size=512K INNODB Specific options INNODB特定选项 innodb_data_home_dir= Use this option if you have a MySQL server with InnoDB support enabled but you do not plan to use it. This will save memory and disk space and speed up some things. 如果您启用了一个支持InnoDB的MySQL服务器,但是您不打算使用它,那么可以使用这个选项。这将节省内存和磁盘空间,并加快一些事情。skip-innodb skip-innodb If set to 1, InnoDB will flush (fsync) the transaction logs to the disk at each commit, which offers full ACID behavior. If you are willing to compromise this safety, and you are running small transactions, you may set this to 0 or 2 to reduce disk I/O to the logs. Value 0 means that the log is only written to the log file and the log file flushed to disk approximately once per second. Value 2 means the log is written to the log file at each commit, but the log file is only flushed to disk approximately once per second. 如果设置为1,InnoDB将在每次提交时将事务日志刷新(fsync)到磁盘,这将提供完整的ACID行为。如果您愿意牺牲这种安全性,并且正在运行小型事务,您可以将其设置为0或2,以将磁盘I/O减少到日志。值0表示日志仅写入日志文件,日志文件大约每秒刷新一次磁盘。值2表示日志在每次提交时写入日志文件,但是日志文件大约每秒只刷新一次磁盘。 innodb_flush_log_at_trx_commit=1 The size of the buffer InnoDB uses for buffering log data. As soon as it is full, InnoDB will have to flush it to disk. As it is flushed once per second anyway, it does not make sense to have it very large (even with long transactions).InnoDB用于缓冲日志数据的缓冲区大小。一旦它满了,InnoDB就必须将它刷新到磁盘。由于它无论如何每秒刷新一次,所以将它设置为非常大的值是没有意义的(即使是长事务)。 innodb_log_buffer_size=5M InnoDB, unlike MyISAM, uses a buffer pool to cache both indexes and row data. The bigger you set this the less disk I/O is needed to access data in tables. On a dedicated database server you may set this parameter up to 80% of the machine physical memory size. Do not set it too large, though, because competition of the physical memory may cause paging in the operating system. Note that on 32bit systems you might be limited to 2-3.5G of user level memory per process, so do not set it too high. 与MyISAM不同,InnoDB使用缓冲池来缓存索引和行数据。设置的值越大,访问表中的数据所需的磁盘I/O就越少。在专用数据库服务器上,可以将该参数设置为机器物理内存大小的80%。但是,不要将它设置得太大,因为物理内存的竞争可能会导致操作系统中的分页。注意,在32位系统上,每个进程的用户级内存可能被限制在2-3.5G,所以不要设置得太高。 innodb_buffer_pool_size=20M Size of each log file in a log group. You should set the combined size of log files to about 25%-100% of your buffer pool size to avoid unneeded buffer pool flush activity on log file overwrite. However, note that a larger logfile size will increase the time needed for the recovery process. 日志组中每个日志文件的大小。您应该将日志文件的合并大小设置为缓冲池大小的25%-100%,以避免在覆盖日志文件时出现不必要的缓冲池刷新活动。但是,请注意,较大的日志文件大小将增加恢复过程所需的时间。 innodb_log_file_size=48M Number of threads allowed inside the InnoDB kernel. The optimal value depends highly on the application, hardware as well as the OS scheduler properties. A too high value may lead to thread thrashing. InnoDB内核中允许的线程数。最优值在很大程度上取决于应用程序、硬件以及OS调度程序属性。过高的值可能导致线程抖动。 innodb_thread_concurrency=9 The increment size (in MB) for extending the size of an auto-extend InnoDB system tablespace file when it becomes full. 增量大小(以MB为单位),用于在表空间满时扩展自动扩展的InnoDB系统表空间文件的大小。 innodb_autoextend_increment=128 The number of regions that the InnoDB buffer pool is divided into. For systems with buffer pools in the multi-gigabyte range, dividing the buffer pool into separate instances can improve concurrency, by reducing contention as different threads read and write to cached pages. InnoDB缓冲池划分的区域数。对于具有多gb缓冲池的系统,将缓冲池划分为单独的实例可以提高并发性,因为不同的线程对缓存页面的读写会减少争用。 innodb_buffer_pool_instances=8 Determines the number of threads that can enter InnoDB concurrently. 确定可以同时进入InnoDB的线程数 innodb_concurrency_tickets=5000 Specifies how long in milliseconds (ms) a block inserted into the old sublist must stay there after its first access before it can be moved to the new sublist. 指定插入到旧子列表中的块必须在第一次访问之后停留多长时间(毫秒),然后才能移动到新子列表。 innodb_old_blocks_time=1000 It specifies the maximum number of .ibd files that MySQL can keep open at one time. The minimum value is 10. 它指定MySQL一次可以打开的.ibd文件的最大数量。最小值是10。 innodb_open_files=300 When this variable is enabled, InnoDB updates statistics during metadata statements. 当启用此变量时,InnoDB会在元数据语句期间更新统计信息。 innodb_stats_on_metadata=0 When innodb_file_per_table is enabled (the default in 5.6.6 and higher), InnoDB stores the data and indexes for each newly created table in a separate .ibd file, rather than in the system tablespace. 当启用innodb_file_per_table(5.6.6或更高版本的默认值)时,InnoDB将每个新创建的表的数据和索引存储在单独的.ibd文件中,而不是系统表空间中。 innodb_file_per_table=1 Use the following list of values: 0 for crc32, 1 for strict_crc32, 2 for innodb, 3 for strict_innodb, 4 for none, 5 for strict_none. 使用以下值列表:0表示crc32, 1表示strict_crc32, 2表示innodb, 3表示strict_innodb, 4表示none, 5表示strict_none。 innodb_checksum_algorithm=0 The number of outstanding connection requests MySQL can have. This option is useful when the main MySQL thread gets many connection requests in a very short time. It then takes some time (although very little) for the main thread to check the connection and start a new thread. The back_log value indicates how many requests can be stacked during this short time before MySQL momentarily stops answering new requests. You need to increase this only if you expect a large number of connections in a short period of time. MySQL可以有多少未完成连接请求。当MySQL主线程在很短的时间内收到许多连接请求时,这个选项非常有用。然后,主线程需要一些时间(尽管很少)来检查连接并启动一个新线程。back_log值表示在MySQL暂时停止响应新请求之前的短时间内可以堆多少个请求。只有当您预期在短时间内会有大量连接时,才需要增加这个值。 back_log=80 If this is set to a nonzero value, all tables are closed every flush_time seconds to free up resources and synchronize unflushed data to disk. This option is best used only on systems with minimal resources. 如果将该值设置为非零值,则每隔flush_time秒关闭所有表,以释放资源并将未刷新的数据同步到磁盘。这个选项最好只在资源最少的系统上使用。 flush_time=0 The minimum size of the buffer that is used for plain index scans, range index scans, and joins that do not use 用于普通索引扫描、范围索引扫描和不使用索引执行全表扫描的连接的缓冲区的最小大小。 indexes and thus perform full table scans. join_buffer_size=200M The maximum size of one packet or any generated or intermediate string, or any parameter sent by the mysql_stmt_send_long_data() C API function. 由mysql_stmt_send_long_data() C API函数发送的一个包或任何生成的或中间字符串或任何参数的最大大小 max_allowed_packet=500M If more than this many successive connection requests from a host are interrupted without a successful connection, the server blocks that host from performing further connections. 如果在没有成功连接的情况下中断了来自主机的多个连续连接请求,则服务器将阻止主机执行进一步的连接。 max_connect_errors=100 Changes the number of file descriptors available to mysqld. You should try increasing the value of this option if mysqld gives you the error "Too many open files". 更改mysqld可用的文件描述符的数量。如果mysqld给您的错误是“打开的文件太多”,您应该尝试增加这个选项的值。 open_files_limit=4161 If you see many sort_merge_passes per second in SHOW GLOBAL STATUS output, you can consider increasing the sort_buffer_size value to speed up ORDER BY or GROUP BY operations that cannot be improved with query optimization or improved indexing. 如果在SHOW GLOBAL STATUS输出中每秒看到许多sort_merge_passes,可以考虑增加sort_buffer_size值,以加快ORDER BY或GROUP BY操作的速度,这些操作无法通过查询优化或改进索引来改进。 sort_buffer_size=1M The number of table definitions (from .frm files) that can be stored in the definition cache. If you use a large number of tables, you can create a large table definition cache to speed up opening of tables. The table definition cache takes less space and does not use file descriptors, unlike the normal table cache. The minimum and default values are both 400. 可以存储在定义缓存中的表定义的数量(来自.frm文件)。如果使用大量表,可以创建一个大型表定义缓存来加速表的打开。与普通的表缓存不同,表定义缓存占用更少的空间,并且不使用文件描述符。最小值和默认值都是400。 table_definition_cache=1400 Specify the maximum size of a row-based binary log event, in bytes. Rows are grouped into events smaller than this size if possible. The value should be a multiple of 256. 指定基于行的二进制日志事件的最大大小,单位为字节。如果可能,将行分组为小于此大小的事件。这个值应该是256的倍数。 binlog_row_event_max_size=8K If the value of this variable is greater than 0, a replication slave synchronizes its master.info file to disk. (using fdatasync()) after every sync_master_info events. 如果该变量的值大于0,则复制奴隶将其主.info文件同步到磁盘。(在每个sync_master_info事件之后使用fdatasync())。 sync_master_info=10000 If the value of this variable is greater than 0, the MySQL server synchronizes its relay log to disk. (using fdatasync()) after every sync_relay_log writes to the relay log. 如果这个变量的值大于0,MySQL服务器将其中继日志同步到磁盘。(在每个sync_relay_log写入到中继日志之后使用fdatasync())。 sync_relay_log=10000 If the value of this variable is greater than 0, a replication slave synchronizes its relay-log.info file to disk. (using fdatasync()) after every sync_relay_log_info transactions. 如果该变量的值大于0,则复制奴隶将其中继日志.info文件同步到磁盘。(在每个sync_relay_log_info事务之后使用fdatasync())。 sync_relay_log_info=10000 Load mysql plugins at start."plugin_x ; plugin_y". 开始时加载mysql插件。“plugin_x;plugin_y” plugin_load The TCP/IP Port the MySQL Server X Protocol will listen on. MySQL服务器X协议将监听TCP/IP端口。 loose_mysqlx_port=33060 本篇文章为转载内容。原文链接:https://blog.csdn.net/mywpython/article/details/89499852。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-08 09:56:02
129
转载
转载文章
...型数据库 支持丰富的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
转载
转载文章
...到持久化系统中(MySQL) 广告点击系统实时分析的意义:因为可以在线实时的看见广告的投放效果,就为广告的更大规模的投入和调整打下了坚实的基础,从而为公司带来最大化的经济回报。 核心需求: 1、实时黑名单动态过滤出有效的用户广告点击行为:因为黑名单用户可能随时出现,所以需要动态更新; 2、在线计算广告点击流量; 3、Top3热门广告; 4、每个广告流量趋势; 5、广告点击用户的区域分布分析 6、最近一分钟的广告点击量; 7、整个广告点击Spark Streaming处理程序724小时运行; 数据格式: 时间、用户、广告、城市等 技术细节: 在线计算用户点击的次数分析,屏蔽IP等; 使用updateStateByKey或者mapWithState进行不同地区广告点击排名的计算; Spark Streaming+Spark SQL+Spark Core等综合分析数据; 使用Window类型的操作; 高可用和性能调优等等; 流量趋势,一般会结合DB等; Spark Core / /package com.tom.spark.SparkApps.sparkstreaming;import java.util.Date;import java.util.HashMap;import java.util.Map;import java.util.Properties;import java.util.Random;import kafka.javaapi.producer.Producer;import kafka.producer.KeyedMessage;import kafka.producer.ProducerConfig;/ 数据生成代码,Kafka Producer产生数据/public class MockAdClickedStat {/ @param args/public static void main(String[] args) {final Random random = new Random();final String[] provinces = new String[]{"Guangdong", "Zhejiang", "Jiangsu", "Fujian"};final Map<String, String[]> cities = new HashMap<String, String[]>();cities.put("Guangdong", new String[]{"Guangzhou", "Shenzhen", "Dongguan"});cities.put("Zhejiang", new String[]{"Hangzhou", "Wenzhou", "Ningbo"});cities.put("Jiangsu", new String[]{"Nanjing", "Suzhou", "Wuxi"});cities.put("Fujian", new String[]{"Fuzhou", "Xiamen", "Sanming"});final String[] ips = new String[] {"192.168.112.240","192.168.112.239","192.168.112.245","192.168.112.246","192.168.112.247","192.168.112.248","192.168.112.249","192.168.112.250","192.168.112.251","192.168.112.252","192.168.112.253","192.168.112.254",};/ Kafka相关的基本配置信息/Properties kafkaConf = new Properties();kafkaConf.put("serializer.class", "kafka.serializer.StringEncoder");kafkaConf.put("metadeta.broker.list", "Master:9092,Worker1:9092,Worker2:9092");ProducerConfig producerConfig = new ProducerConfig(kafkaConf);final Producer<Integer, String> producer = new Producer<Integer, String>(producerConfig);new Thread(new Runnable() {public void run() {while(true) {//在线处理广告点击流的基本数据格式:timestamp、ip、userID、adID、province、cityLong timestamp = new Date().getTime();String ip = ips[random.nextInt(12)]; //可以采用网络上免费提供的ip库int userID = random.nextInt(10000);int adID = random.nextInt(100);String province = provinces[random.nextInt(4)];String city = cities.get(province)[random.nextInt(3)];String clickedAd = timestamp + "\t" + ip + "\t" + userID + "\t" + adID + "\t" + province + "\t" + city;producer.send(new KeyedMessage<Integer, String>("AdClicked", clickedAd));try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }} }).start();} } package com.tom.spark.SparkApps.sparkstreaming;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.LinkedBlockingQueue;import kafka.serializer.StringDecoder;import org.apache.spark.SparkConf;import org.apache.spark.api.java.JavaPairRDD;import org.apache.spark.api.java.JavaRDD;import org.apache.spark.api.java.JavaSparkContext;import org.apache.spark.api.java.function.Function;import org.apache.spark.api.java.function.Function2;import org.apache.spark.api.java.function.PairFunction;import org.apache.spark.api.java.function.VoidFunction;import org.apache.spark.sql.DataFrame;import org.apache.spark.sql.Row;import org.apache.spark.sql.RowFactory;import org.apache.spark.sql.hive.HiveContext;import org.apache.spark.sql.types.DataTypes;import org.apache.spark.sql.types.StructType;import org.apache.spark.streaming.Durations;import org.apache.spark.streaming.api.java.JavaDStream;import org.apache.spark.streaming.api.java.JavaPairDStream;import org.apache.spark.streaming.api.java.JavaPairInputDStream;import org.apache.spark.streaming.api.java.JavaStreamingContext;import org.apache.spark.streaming.api.java.JavaStreamingContextFactory;import org.apache.spark.streaming.kafka.KafkaUtils;import com.google.common.base.Optional;import scala.Tuple2;/ 数据处理,Kafka消费者/public class AdClickedStreamingStats {/ @param args/public static void main(String[] args) {// TODO Auto-generated method stub//好处:1、checkpoint 2、工厂final SparkConf conf = new SparkConf().setAppName("SparkStreamingOnKafkaDirect").setMaster("hdfs://Master:7077/");final String checkpointDirectory = "hdfs://Master:9000/library/SparkStreaming/CheckPoint_Data";JavaStreamingContextFactory factory = new JavaStreamingContextFactory() {public JavaStreamingContext create() {// TODO Auto-generated method stubreturn createContext(checkpointDirectory, conf);} };/ 可以从失败中恢复Driver,不过还需要指定Driver这个进程运行在Cluster,并且在提交应用程序的时候制定--supervise;/JavaStreamingContext javassc = JavaStreamingContext.getOrCreate(checkpointDirectory, factory);/ 第三步:创建Spark Streaming输入数据来源input Stream: 1、数据输入来源可以基于File、HDFS、Flume、Kafka、Socket等 2、在这里我们指定数据来源于网络Socket端口,Spark Streaming连接上该端口并在运行的时候一直监听该端口的数据 (当然该端口服务首先必须存在),并且在后续会根据业务需要不断有数据产生(当然对于Spark Streaming 应用程序的运行而言,有无数据其处理流程都是一样的) 3、如果经常在每间隔5秒钟没有数据的话不断启动空的Job其实会造成调度资源的浪费,因为并没有数据需要发生计算;所以 实际的企业级生成环境的代码在具体提交Job前会判断是否有数据,如果没有的话就不再提交Job;///创建Kafka元数据来让Spark Streaming这个Kafka Consumer利用Map<String, String> kafkaParameters = new HashMap<String, String>();kafkaParameters.put("metadata.broker.list", "Master:9092,Worker1:9092,Worker2:9092");Set<String> topics = new HashSet<String>();topics.add("SparkStreamingDirected");JavaPairInputDStream<String, String> adClickedStreaming = KafkaUtils.createDirectStream(javassc, String.class, String.class, StringDecoder.class, StringDecoder.class,kafkaParameters, topics);/因为要对黑名单进行过滤,而数据是在RDD中的,所以必然使用transform这个函数; 但是在这里我们必须使用transformToPair,原因是读取进来的Kafka的数据是Pair<String,String>类型, 另一个原因是过滤后的数据要进行进一步处理,所以必须是读进的Kafka数据的原始类型 在此再次说明,每个Batch Duration中实际上讲输入的数据就是被一个且仅被一个RDD封装的,你可以有多个 InputDStream,但其实在产生job的时候,这些不同的InputDStream在Batch Duration中就相当于Spark基于HDFS 数据操作的不同文件来源而已罢了。/JavaPairDStream<String, String> filteredadClickedStreaming = adClickedStreaming.transformToPair(new Function<JavaPairRDD<String,String>, JavaPairRDD<String,String>>() {public JavaPairRDD<String, String> call(JavaPairRDD<String, String> rdd) throws Exception {/ 在线黑名单过滤思路步骤: 1、从数据库中获取黑名单转换成RDD,即新的RDD实例封装黑名单数据; 2、然后把代表黑名单的RDD的实例和Batch Duration产生的RDD进行Join操作, 准确的说是进行leftOuterJoin操作,也就是说使用Batch Duration产生的RDD和代表黑名单的RDD实例进行 leftOuterJoin操作,如果两者都有内容的话,就会是true,否则的话就是false 我们要留下的是leftOuterJoin结果为false; /final List<String> blackListNames = new ArrayList<String>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();jdbcWrapper.doQuery("SELECT FROM blacklisttable", null, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {while(result.next()){blackListNames.add(result.getString(1));} }});List<Tuple2<String, Boolean>> blackListTuple = new ArrayList<Tuple2<String,Boolean>>();for(String name : blackListNames) {blackListTuple.add(new Tuple2<String, Boolean>(name, true));}List<Tuple2<String, Boolean>> blacklistFromListDB = blackListTuple; //数据来自于查询的黑名单表并且映射成为<String, Boolean>JavaSparkContext jsc = new JavaSparkContext(rdd.context());/ 黑名单的表中只有userID,但是如果要进行join操作的话就必须是Key-Value,所以在这里我们需要 基于数据表中的数据产生Key-Value类型的数据集合/JavaPairRDD<String, Boolean> blackListRDD = jsc.parallelizePairs(blacklistFromListDB);/ 进行操作的时候肯定是基于userID进行join,所以必须把传入的rdd进行mapToPair操作转化成为符合格式的RDD/JavaPairRDD<String, Tuple2<String, String>> rdd2Pair = rdd.mapToPair(new PairFunction<Tuple2<String,String>, String, Tuple2<String, String>>() {public Tuple2<String, Tuple2<String, String>> call(Tuple2<String, String> t) throws Exception {// TODO Auto-generated method stubString userID = t._2.split("\t")[2];return new Tuple2<String, Tuple2<String,String>>(userID, t);} });JavaPairRDD<String, Tuple2<Tuple2<String, String>, Optional<Boolean>>> joined = rdd2Pair.leftOuterJoin(blackListRDD);JavaPairRDD<String, String> result = joined.filter(new Function<Tuple2<String,Tuple2<Tuple2<String,String>,Optional<Boolean>>>, Boolean>() {public Boolean call(Tuple2<String, Tuple2<Tuple2<String, String>, Optional<Boolean>>> tuple)throws Exception {// TODO Auto-generated method stubOptional<Boolean> optional = tuple._2._2;if(optional.isPresent() && optional.get()){return false;} else {return true;} }}).mapToPair(new PairFunction<Tuple2<String,Tuple2<Tuple2<String,String>,Optional<Boolean>>>, String, String>() {public Tuple2<String, String> call(Tuple2<String, Tuple2<Tuple2<String, String>, Optional<Boolean>>> t)throws Exception {// TODO Auto-generated method stubreturn t._2._1;} });return result;} });//广告点击的基本数据格式:timestamp、ip、userID、adID、province、cityJavaPairDStream<String, Long> pairs = filteredadClickedStreaming.mapToPair(new PairFunction<Tuple2<String,String>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, String> t) throws Exception {String[] splited=t._2.split("\t");String timestamp = splited[0]; //YYYY-MM-DDString ip = splited[1];String userID = splited[2];String adID = splited[3];String province = splited[4];String city = splited[5]; String clickedRecord = timestamp + "_" +ip + "_"+userID+"_"+adID+"_"+province +"_"+city;return new Tuple2<String, Long>(clickedRecord, 1L);} });/ 第4.3步:在单词实例计数为1基础上,统计每个单词在文件中出现的总次数/JavaPairDStream<String, Long> adClickedUsers= pairs.reduceByKey(new Function2<Long, Long, Long>() {public Long call(Long i1, Long i2) throws Exception{return i1 + i2;} });/判断有效的点击,复杂化的采用机器学习训练模型进行在线过滤 简单的根据ip判断1天不超过100次;也可以通过一个batch duration的点击次数判断是否非法广告点击,通过一个batch来判断是不完整的,还需要一天的数据也可以每一个小时来判断。/JavaPairDStream<String, Long> filterClickedBatch = adClickedUsers.filter(new Function<Tuple2<String,Long>, Boolean>() {public Boolean call(Tuple2<String, Long> v1) throws Exception {if (1 < v1._2){//更新一些黑名单的数据库表return false;} else { return true;} }});//filterClickedBatch.print();//写入数据库filterClickedBatch.foreachRDD(new Function<JavaPairRDD<String,Long>, Void>() {public Void call(JavaPairRDD<String, Long> rdd) throws Exception {rdd.foreachPartition(new VoidFunction<Iterator<Tuple2<String,Long>>>() {public void call(Iterator<Tuple2<String, Long>> partition) throws Exception {//使用数据库连接池的高效读写数据库的方式将数据写入数据库mysql//例如一次插入 1000条 records,使用insertBatch 或 updateBatch//插入的用户数据信息:userID,adID,clickedCount,time//这里面有一个问题,可能出现两条记录的key是一样的,此时需要更新累加操作List<UserAdClicked> userAdClickedList = new ArrayList<UserAdClicked>();while(partition.hasNext()) {Tuple2<String, Long> record = partition.next();String[] splited = record._1.split("\t");UserAdClicked userClicked = new UserAdClicked();userClicked.setTimestamp(splited[0]);userClicked.setIp(splited[1]);userClicked.setUserID(splited[2]);userClicked.setAdID(splited[3]);userClicked.setProvince(splited[4]);userClicked.setCity(splited[5]);userAdClickedList.add(userClicked);}final List<UserAdClicked> inserting = new ArrayList<UserAdClicked>();final List<UserAdClicked> updating = new ArrayList<UserAdClicked>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();//表的字段timestamp、ip、userID、adID、province、city、clickedCountfor(final UserAdClicked clicked : userAdClickedList) {jdbcWrapper.doQuery("SELECT clickedCount FROM adclicked WHERE"+ " timestamp =? AND userID = ? AND adID = ?",new Object[]{clicked.getTimestamp(), clicked.getUserID(),clicked.getAdID()}, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {// TODO Auto-generated method stubif(result.next()) {long count = result.getLong(1);clicked.setClickedCount(count);updating.add(clicked);} else {inserting.add(clicked);clicked.setClickedCount(1L);} }});}//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(UserAdClicked insertRecord : inserting) {insertParametersList.add(new Object[] {insertRecord.getTimestamp(),insertRecord.getIp(),insertRecord.getUserID(),insertRecord.getAdID(),insertRecord.getProvince(),insertRecord.getCity(),insertRecord.getClickedCount()});}jdbcWrapper.doBatch("INSERT INTO adclicked VALUES(?, ?, ?, ?, ?, ?, ?)", insertParametersList);//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> updateParametersList = new ArrayList<Object[]>();for(UserAdClicked updateRecord : updating) {updateParametersList.add(new Object[] {updateRecord.getTimestamp(),updateRecord.getIp(),updateRecord.getUserID(),updateRecord.getAdID(),updateRecord.getProvince(),updateRecord.getCity(),updateRecord.getClickedCount() + 1});}jdbcWrapper.doBatch("UPDATE adclicked SET clickedCount = ? WHERE"+ " timestamp =? AND ip = ? AND userID = ? AND adID = ? "+ "AND province = ? AND city = ?", updateParametersList);} });return null;} });//再次过滤,从数据库中读取数据过滤黑名单JavaPairDStream<String, Long> blackListBasedOnHistory = filterClickedBatch.filter(new Function<Tuple2<String,Long>, Boolean>() {public Boolean call(Tuple2<String, Long> v1) throws Exception {//广告点击的基本数据格式:timestamp,ip,userID,adID,province,cityString[] splited = v1._1.split("\t"); //提取key值String date =splited[0];String userID =splited[2];String adID =splited[3];//查询一下数据库同一个用户同一个广告id点击量超过50次列入黑名单//接下来 根据date、userID、adID条件去查询用户点击广告的数据表,获得总的点击次数//这个时候基于点击次数判断是否属于黑名单点击int clickedCountTotalToday = 81 ;if (clickedCountTotalToday > 50) {return true;}else {return false ;} }});//map操作,找出用户的idJavaDStream<String> blackListuserIDBasedInBatchOnhistroy =blackListBasedOnHistory.map(new Function<Tuple2<String,Long>, String>() {public String call(Tuple2<String, Long> v1) throws Exception {// TODO Auto-generated method stubreturn v1._1.split("\t")[2];} });//有一个问题,数据可能重复,在一个partition里面重复,这个好办;//但多个partition不能保证一个用户重复,需要对黑名单的整个rdd进行去重操作。//rdd去重了,partition也就去重了,一石二鸟,一箭双雕// 找出了黑名单,下一步就写入黑名单数据库表中JavaDStream<String> blackListUniqueuserBasedInBatchOnhistroy = blackListuserIDBasedInBatchOnhistroy.transform(new Function<JavaRDD<String>, JavaRDD<String>>() {public JavaRDD<String> call(JavaRDD<String> rdd) throws Exception {// TODO Auto-generated method stubreturn rdd.distinct();} });// 下一步写入到数据表中blackListUniqueuserBasedInBatchOnhistroy.foreachRDD(new Function<JavaRDD<String>, Void>() {public Void call(JavaRDD<String> rdd) throws Exception {rdd.foreachPartition(new VoidFunction<Iterator<String>>() {public void call(Iterator<String> t) throws Exception {// TODO Auto-generated method stub//插入的用户信息可以只包含:useID//此时直接插入黑名单数据表即可。//写入数据库List<Object[]> blackList = new ArrayList<Object[]>();while(t.hasNext()) {blackList.add(new Object[]{t.next()});}JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();jdbcWrapper.doBatch("INSERT INTO blacklisttable values (?)", blackList);} });return null;} });/广告点击累计动态更新,每个updateStateByKey都会在Batch Duration的时间间隔的基础上进行广告点击次数的更新, 更新之后我们一般都会持久化到外部存储设备上,在这里我们存储到MySQL数据库中/JavaPairDStream<String, Long> updateStateByKeyDSteam = filteredadClickedStreaming.mapToPair(new PairFunction<Tuple2<String,String>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, String> t)throws Exception {String[] splited=t._2.split("\t");String timestamp = splited[0]; //YYYY-MM-DDString ip = splited[1];String userID = splited[2];String adID = splited[3];String province = splited[4];String city = splited[5]; String clickedRecord = timestamp + "_" +ip + "_"+userID+"_"+adID+"_"+province +"_"+city;return new Tuple2<String, Long>(clickedRecord, 1L);} }).updateStateByKey(new Function2<List<Long>, Optional<Long>, Optional<Long>>() {public Optional<Long> call(List<Long> v1, Optional<Long> v2)throws Exception {// v1:当前的Key在当前的Batch Duration中出现的次数的集合,例如{1,1,1,。。。,1}// v2:当前的Key在以前的Batch Duration中积累下来的结果;Long clickedTotalHistory = 0L; if(v2.isPresent()){clickedTotalHistory = v2.get();}for(Long one : v1) {clickedTotalHistory += one;}return Optional.of(clickedTotalHistory);} });updateStateByKeyDSteam.foreachRDD(new Function<JavaPairRDD<String,Long>, Void>() {public Void call(JavaPairRDD<String, Long> rdd) throws Exception {rdd.foreachPartition(new VoidFunction<Iterator<Tuple2<String,Long>>>() {public void call(Iterator<Tuple2<String, Long>> partition) throws Exception {//使用数据库连接池的高效读写数据库的方式将数据写入数据库mysql//例如一次插入 1000条 records,使用insertBatch 或 updateBatch//插入的用户数据信息:timestamp、adID、province、city//这里面有一个问题,可能出现两条记录的key是一样的,此时需要更新累加操作List<AdClicked> AdClickedList = new ArrayList<AdClicked>();while(partition.hasNext()) {Tuple2<String, Long> record = partition.next();String[] splited = record._1.split("\t");AdClicked adClicked = new AdClicked();adClicked.setTimestamp(splited[0]);adClicked.setAdID(splited[1]);adClicked.setProvince(splited[2]);adClicked.setCity(splited[3]);adClicked.setClickedCount(record._2);AdClickedList.add(adClicked);}final List<AdClicked> inserting = new ArrayList<AdClicked>();final List<AdClicked> updating = new ArrayList<AdClicked>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();//表的字段timestamp、ip、userID、adID、province、city、clickedCountfor(final AdClicked clicked : AdClickedList) {jdbcWrapper.doQuery("SELECT clickedCount FROM adclickedcount WHERE"+ " timestamp = ? AND adID = ? AND province = ? AND city = ?",new Object[]{clicked.getTimestamp(), clicked.getAdID(),clicked.getProvince(), clicked.getCity()}, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {// TODO Auto-generated method stubif(result.next()) {long count = result.getLong(1);clicked.setClickedCount(count);updating.add(clicked);} else {inserting.add(clicked);clicked.setClickedCount(1L);} }});}//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(AdClicked insertRecord : inserting) {insertParametersList.add(new Object[] {insertRecord.getTimestamp(),insertRecord.getAdID(),insertRecord.getProvince(),insertRecord.getCity(),insertRecord.getClickedCount()});}jdbcWrapper.doBatch("INSERT INTO adclickedcount VALUES(?, ?, ?, ?, ?)", insertParametersList);//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> updateParametersList = new ArrayList<Object[]>();for(AdClicked updateRecord : updating) {updateParametersList.add(new Object[] {updateRecord.getClickedCount(),updateRecord.getTimestamp(),updateRecord.getAdID(),updateRecord.getProvince(),updateRecord.getCity()});}jdbcWrapper.doBatch("UPDATE adclickedcount SET clickedCount = ? WHERE"+ " timestamp =? AND adID = ? AND province = ? AND city = ?", updateParametersList);} });return null;} });/ 对广告点击进行TopN计算,计算出每天每个省份Top5排名的广告 因为我们直接对RDD进行操作,所以使用了transfomr算子;/updateStateByKeyDSteam.transform(new Function<JavaPairRDD<String,Long>, JavaRDD<Row>>() {public JavaRDD<Row> call(JavaPairRDD<String, Long> rdd) throws Exception {JavaRDD<Row> rowRDD = rdd.mapToPair(new PairFunction<Tuple2<String,Long>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, Long> t)throws Exception {// TODO Auto-generated method stubString[] splited=t._1.split("_");String timestamp = splited[0]; //YYYY-MM-DDString adID = splited[3];String province = splited[4];String clickedRecord = timestamp + "_" + adID + "_" + province;return new Tuple2<String, Long>(clickedRecord, t._2);} }).reduceByKey(new Function2<Long, Long, Long>() {public Long call(Long v1, Long v2) throws Exception {// TODO Auto-generated method stubreturn v1 + v2;} }).map(new Function<Tuple2<String,Long>, Row>() {public Row call(Tuple2<String, Long> v1) throws Exception {// TODO Auto-generated method stubString[] splited=v1._1.split("_");String timestamp = splited[0]; //YYYY-MM-DDString adID = splited[3];String province = splited[4];return RowFactory.create(timestamp, adID, province, v1._2);} });StructType structType = DataTypes.createStructType(Arrays.asList(DataTypes.createStructField("timestamp", DataTypes.StringType, true),DataTypes.createStructField("adID", DataTypes.StringType, true),DataTypes.createStructField("province", DataTypes.StringType, true),DataTypes.createStructField("clickedCount", DataTypes.LongType, true)));HiveContext hiveContext = new HiveContext(rdd.context());DataFrame df = hiveContext.createDataFrame(rowRDD, structType);df.registerTempTable("topNTableSource");DataFrame result = hiveContext.sql("SELECT timestamp, adID, province, clickedCount, FROM"+ " (SELECT timestamp, adID, province,clickedCount, "+ "ROW_NUMBER() OVER(PARTITION BY province ORDER BY clickeCount DESC) rank "+ "FROM topNTableSource) subquery "+ "WHERE rank <= 5");return result.toJavaRDD();} }).foreachRDD(new Function<JavaRDD<Row>, Void>() {public Void call(JavaRDD<Row> rdd) throws Exception {// TODO Auto-generated method stubrdd.foreachPartition(new VoidFunction<Iterator<Row>>() {public void call(Iterator<Row> t) throws Exception {// TODO Auto-generated method stubList<AdProvinceTopN> adProvinceTopN = new ArrayList<AdProvinceTopN>();while(t.hasNext()) {Row row = t.next();AdProvinceTopN item = new AdProvinceTopN();item.setTimestamp(row.getString(0));item.setAdID(row.getString(1));item.setProvince(row.getString(2));item.setClickedCount(row.getLong(3));adProvinceTopN.add(item);}// final List<AdProvinceTopN> inserting = new ArrayList<AdProvinceTopN>();// final List<AdProvinceTopN> updating = new ArrayList<AdProvinceTopN>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();Set<String> set = new HashSet<String>();for(AdProvinceTopN item: adProvinceTopN){set.add(item.getTimestamp() + "_" + item.getProvince());}//表的字段timestamp、adID、province、clickedCountArrayList<Object[]> deleteParametersList = new ArrayList<Object[]>();for(String deleteRecord : set) {String[] splited = deleteRecord.split("_");deleteParametersList.add(new Object[]{splited[0],splited[1]});}jdbcWrapper.doBatch("DELETE FROM adprovincetopn WHERE timestamp = ? AND province = ?", deleteParametersList);//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(AdProvinceTopN insertRecord : adProvinceTopN) {insertParametersList.add(new Object[] {insertRecord.getClickedCount(),insertRecord.getTimestamp(),insertRecord.getAdID(),insertRecord.getProvince()});}jdbcWrapper.doBatch("INSERT INTO adprovincetopn VALUES (?, ?, ?, ?)", insertParametersList);} });return null;} });/ 计算过去半个小时内广告点击的趋势 广告点击的基本数据格式:timestamp、ip、userID、adID、province、city/filteredadClickedStreaming.mapToPair(new PairFunction<Tuple2<String,String>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, String> t)throws Exception {String splited[] = t._2.split("\t");String adID = splited[3];String time = splited[0]; //Todo:后续需要重构代码实现时间戳和分钟的转换提取。此处需要提取出该广告的点击分钟单位return new Tuple2<String, Long>(time + "_" + adID, 1L);} }).reduceByKeyAndWindow(new Function2<Long, Long, Long>() {public Long call(Long v1, Long v2) throws Exception {// TODO Auto-generated method stubreturn v1 + v2;} }, new Function2<Long, Long, Long>() {public Long call(Long v1, Long v2) throws Exception {// TODO Auto-generated method stubreturn v1 - v2;} }, Durations.minutes(30), Durations.milliseconds(5)).foreachRDD(new Function<JavaPairRDD<String,Long>, Void>() {public Void call(JavaPairRDD<String, Long> rdd) throws Exception {// TODO Auto-generated method stubrdd.foreachPartition(new VoidFunction<Iterator<Tuple2<String,Long>>>() {public void call(Iterator<Tuple2<String, Long>> partition)throws Exception {List<AdTrendStat> adTrend = new ArrayList<AdTrendStat>();// TODO Auto-generated method stubwhile(partition.hasNext()) {Tuple2<String, Long> record = partition.next();String[] splited = record._1.split("_");String time = splited[0];String adID = splited[1];Long clickedCount = record._2;/ 在插入数据到数据库的时候具体需要哪些字段?time、adID、clickedCount; 而我们通过J2EE技术进行趋势绘图的时候肯定是需要年、月、日、时、分这个维度的,所以我们在这里需要 年月日、小时、分钟这些时间维度;/AdTrendStat adTrendStat = new AdTrendStat();adTrendStat.setAdID(adID);adTrendStat.setClickedCount(clickedCount);adTrendStat.set_date(time); //Todo:获取年月日adTrendStat.set_hour(time); //Todo:获取小时adTrendStat.set_minute(time);//Todo:获取分钟adTrend.add(adTrendStat);}final List<AdTrendStat> inserting = new ArrayList<AdTrendStat>();final List<AdTrendStat> updating = new ArrayList<AdTrendStat>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();//表的字段timestamp、ip、userID、adID、province、city、clickedCountfor(final AdTrendStat trend : adTrend) {final AdTrendCountHistory adTrendhistory = new AdTrendCountHistory();jdbcWrapper.doQuery("SELECT clickedCount FROM adclickedtrend WHERE"+ " date =? AND hour = ? AND minute = ? AND AdID = ?",new Object[]{trend.get_date(), trend.get_hour(), trend.get_minute(),trend.getAdID()}, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {// TODO Auto-generated method stubif(result.next()) {long count = result.getLong(1);adTrendhistory.setClickedCountHistoryLong(count);updating.add(trend);} else { inserting.add(trend);} }});}//表的字段date、hour、minute、adID、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(AdTrendStat insertRecord : inserting) {insertParametersList.add(new Object[] {insertRecord.get_date(),insertRecord.get_hour(),insertRecord.get_minute(),insertRecord.getAdID(),insertRecord.getClickedCount()});}jdbcWrapper.doBatch("INSERT INTO adclickedtrend VALUES(?, ?, ?, ?, ?)", insertParametersList);//表的字段date、hour、minute、adID、clickedCountList<Object[]> updateParametersList = new ArrayList<Object[]>();for(AdTrendStat updateRecord : updating) {updateParametersList.add(new Object[] {updateRecord.getClickedCount(),updateRecord.get_date(),updateRecord.get_hour(),updateRecord.get_minute(),updateRecord.getAdID()});}jdbcWrapper.doBatch("UPDATE adclickedtrend SET clickedCount = ? WHERE"+ " date =? AND hour = ? AND minute = ? AND AdID = ?", updateParametersList);} });return null;} });;/ Spark Streaming 执行引擎也就是Driver开始运行,Driver启动的时候是位于一条新的线程中的,当然其内部有消息循环体,用于 接收应用程序本身或者Executor中的消息,/javassc.start();javassc.awaitTermination();javassc.close();}private static JavaStreamingContext createContext(String checkpointDirectory, SparkConf conf) {// If you do not see this printed, that means the StreamingContext has been loaded// from the new checkpointSystem.out.println("Creating new context");// Create the context with a 5 second batch sizeJavaStreamingContext ssc = new JavaStreamingContext(conf, Durations.seconds(10));ssc.checkpoint(checkpointDirectory);return ssc;} }class JDBCWrapper {private static JDBCWrapper jdbcInstance = null;private static LinkedBlockingQueue<Connection> dbConnectionPool = new LinkedBlockingQueue<Connection>();static {try {Class.forName("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} }public static JDBCWrapper getJDBCInstance() {if(jdbcInstance == null) {synchronized (JDBCWrapper.class) {if(jdbcInstance == null) {jdbcInstance = new JDBCWrapper();} }}return jdbcInstance; }private JDBCWrapper() {for(int i = 0; i < 10; i++){try {Connection conn = DriverManager.getConnection("jdbc:mysql://Master:3306/sparkstreaming","root", "root");dbConnectionPool.put(conn);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} } }public synchronized Connection getConnection() {while(0 == dbConnectionPool.size()){try {Thread.sleep(20);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }return dbConnectionPool.poll();}public int[] doBatch(String sqlText, List<Object[]> paramsList){Connection conn = getConnection();PreparedStatement preparedStatement = null;int[] result = null;try {conn.setAutoCommit(false);preparedStatement = conn.prepareStatement(sqlText);for(Object[] parameters: paramsList) {for(int i = 0; i < parameters.length; i++){preparedStatement.setObject(i + 1, parameters[i]);} preparedStatement.addBatch();}result = preparedStatement.executeBatch();conn.commit();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if(preparedStatement != null) {try {preparedStatement.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} }if(conn != null) {try {dbConnectionPool.put(conn);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }}return result; }public void doQuery(String sqlText, Object[] paramsList, ExecuteCallBack callback){Connection conn = getConnection();PreparedStatement preparedStatement = null;ResultSet result = null;try {preparedStatement = conn.prepareStatement(sqlText);for(int i = 0; i < paramsList.length; i++){preparedStatement.setObject(i + 1, paramsList[i]);} result = preparedStatement.executeQuery();try {callback.resultCallBack(result);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} } catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if(preparedStatement != null) {try {preparedStatement.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} }if(conn != null) {try {dbConnectionPool.put(conn);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }} }}interface ExecuteCallBack {void resultCallBack(ResultSet result) throws Exception;}class UserAdClicked {private String timestamp;private String ip;private String userID;private String adID;private String province;private String city;private Long clickedCount;public String getTimestamp() {return timestamp;}public void setTimestamp(String timestamp) {this.timestamp = timestamp;}public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public String getUserID() {return userID;}public void setUserID(String userID) {this.userID = userID;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdClicked {private String timestamp;private String adID;private String province;private String city;private Long clickedCount;public String getTimestamp() {return timestamp;}public void setTimestamp(String timestamp) {this.timestamp = timestamp;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdProvinceTopN {private String timestamp;private String adID;private String province;private Long clickedCount;public String getTimestamp() {return timestamp;}public void setTimestamp(String timestamp) {this.timestamp = timestamp;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdTrendStat {private String _date;private String _hour;private String _minute;private String adID;private Long clickedCount;public String get_date() {return _date;}public void set_date(String _date) {this._date = _date;}public String get_hour() {return _hour;}public void set_hour(String _hour) {this._hour = _hour;}public String get_minute() {return _minute;}public void set_minute(String _minute) {this._minute = _minute;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdTrendCountHistory{private Long clickedCountHistoryLong;public Long getClickedCountHistoryLong() {return clickedCountHistoryLong;}public void setClickedCountHistoryLong(Long clickedCountHistoryLong) {this.clickedCountHistoryLong = clickedCountHistoryLong;} } 本篇文章为转载内容。原文链接:https://blog.csdn.net/tom_8899_li/article/details/71194434。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-02-14 19:16:35
297
转载
Saiku
...本的作用就是调用MySQL的dump命令,生成数据库的备份文件。这样就不用担心忘记备份了,挺方便的。 bash 编辑crontab crontab -e 添加如下行,每周日凌晨两点执行一次备份 0 2 0 /usr/bin/mysqldump -u username -p'password' database_name > /path/to/backup/db_backup_$(date +\%Y\%m\%d).sql 4. 恢复策略的设计 现在我们已经了解了为什么需要一个好的恢复计划,接下来谈谈如何设计这样一个计划。首先,你需要明确哪些数据是最关键的。然后,根据这些数据的重要程度制定相应的恢复策略。比如说,如果你每天都在更新的数据,那就得时不时地备份一下,甚至可以每一小时就来一次。但如果是那种好几天都不动弹的数据,那就可以放宽心,不用那么频繁地备份了。 另外,别忘了测试你的恢复计划!只有经过实践检验的恢复流程才能真正发挥作用。你可以定期模拟一些常见故障场景,看看你的系统是否能够顺利恢复到正常状态。 5. 代码示例 为了让大家更好地理解,下面我会给出几个具体的代码示例,展示如何使用Saiku API来进行数据恢复操作。 示例1:连接到Saiku服务器 java import org.saiku.service.datasource.IDatasourceService; import org.saiku.service.datasource.MondrianDatasource; public class SaikuConnectionExample { public static void main(String[] args) { // 假设我们已经有了一个名为"myDataSource"的数据源实例 MondrianDatasource myDataSource = new MondrianDatasource(); myDataSource.setName("myDataSource"); // 使用datasource服务保存数据源配置 IDatasourceService datasourceService = ...; // 获取datasource服务实例 datasourceService.save(myDataSource); } } 示例2:从备份文件中恢复数据 这里假设你已经有一个包含所有必要信息的备份文件,比如SQL脚本。 java import java.io.BufferedReader; import java.io.FileReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class RestoreFromBackupExample { public static void main(String[] args) { try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password")) { Statement stmt = conn.createStatement(); // 读取备份文件内容并执行 BufferedReader reader = new BufferedReader(new FileReader("/path/to/backup/file.sql")); String line; StringBuilder sql = new StringBuilder(); while ((line = reader.readLine()) != null) { sql.append(line); if (line.trim().endsWith(";")) { stmt.execute(sql.toString()); sql.setLength(0); // 清空StringBuilder } } reader.close(); } catch (Exception e) { e.printStackTrace(); } } } 6. 结语 好了,到这里我们的讨论就告一段落了。希望今天聊的这些能让大家更看重系统恢复计划,也赶紧动手做点啥来提高自己的数据安全,毕竟防患于未然嘛。记住,预防总是胜于治疗,提前做好准备总比事后补救要好得多! 最后,如果你有任何想法或建议,欢迎随时与我交流。数据分析的世界充满了无限可能,让我们一起探索吧! --- 以上就是本次关于“Saiku的系统恢复计划不充分”的全部内容。希望这篇文章能够对你有所帮助,也欢迎大家提出宝贵的意见和建议。
2024-11-18 15:31:47
36
寂静森林
MySQL
...深入理解了如何在MySQL中写入数据后,我们可以进一步关注数据库管理系统的最新动态和最佳实践。近日,MySQL 8.0版本引入了一系列重大更新,包括对安全性、性能以及SQL语法的改进。例如,新的窗口函数提供了更强大的数据分析能力,而Caching_sha2_password身份验证插件则增强了数据库连接的安全性。 同时,随着云技术的发展,各大云服务商如阿里云、AWS等纷纷推出MySQL托管服务,用户无需关心底层服务器运维,即可轻松实现高可用性和扩展性。对于开发人员来说,了解如何在云环境下高效地进行数据写入操作,比如利用批量插入API减少网络延迟,或者通过参数化查询防止SQL注入攻击,成为了必不可少的知识点。 此外,关于数据库优化策略,一篇来自Oracle官方博客的文章《Maximizing MySQL Performance: Tips from the Experts》深度解读了如何通过索引设计、查询优化以及合理使用存储引擎等手段提升MySQL的数据写入效率。文中引用了大量实战案例,为数据库管理员和开发者提供了宝贵的参考经验。 综上所述,在掌握基本的MySQL数据写入操作之外,紧跟数据库技术发展的步伐,关注安全增强、云服务特性及性能优化技巧,是现代开发者必备的技能升级路径。
2023-06-05 22:29:31
72
算法侠
MySQL
...解如何检测和安装MySQL后,我们进一步关注MySQL的最新动态与应用场景。近日,MySQL 8.0版本因其显著的性能提升和增强的安全特性受到了业界广泛关注。它引入了窗口函数、原子DDL操作以及对JSON的支持大幅增强等新特性,使得数据处理更为高效便捷。此外,MySQL 8.0在安全性方面新增了 caching_sha2_password 身份验证插件,有效提升了数据库账户的安全级别。 同时,随着云服务的发展,MySQL也在各大云平台如AWS RDS、阿里云RDS等上提供了更加灵活且易于管理的服务选项。企业用户可以根据自身需求选择适合的部署方式,实现资源按需分配与扩展。 而对于开发者而言,掌握MySQL优化技巧及其实战应用至关重要。例如,合理设计数据库表结构、熟练运用索引策略、适时进行查询优化等方法,能够在很大程度上提高MySQL数据库在高并发场景下的响应速度和稳定性。 总的来说,MySQL作为全球最广泛使用的开源关系型数据库之一,在不断迭代升级中持续赋能各行业业务发展,而深入理解和熟练掌握MySQL的各项功能,无疑将为企业和个人开发者在大数据时代带来更强竞争力。
2023-02-06 16:45:27
103
程序媛
MySQL
MySQL是一种普遍的关系型数据库管理系统,时常应用于构建Web应用程序。在构建或管理MySQL数据库时,时常需要查看MySQL的版本号。以下是一些方法来查找MySQL的版本号。 方法1:通过命令行查找MySQL版本号。 1. 启动终端或命令行窗口。 2. 键入命令 "mysql --version",然后按Enter键。 3. MySQL版本号将显示在命令行窗口中。 例如: $ mysql --version mysql Ver 14.14 Distrib 5.7.19, for Linux (x86_64) using EditLine wrapper 方法2:通过MySQL命令行客户端查找MySQL版本号。 1. 启动MySQL命令行客户端。 2. 键入命令 "SELECT VERSION();",然后按Enter键。 3. MySQL版本号将显示在MySQL命令行客户端中。 例如: mysql>SELECT VERSION(); +-------------------------+ | VERSION() | +-------------------------+ | 5.7.19-0ubuntu0.16.04.1 | +-------------------------+ 1 row in set (0.00 sec) 无论您选择哪种方法,从中获得的MySQL版本号都是相同的。查看MySQL版本号是一个重要的工作,因为MySQL的版本可能会改变,从而可能会引起应用程序或Web应用程序的行为也随之发生改变。
2023-10-03 21:22:15
106
软件工程师
MySQL
在深入了解了MySQL数据库中表基本信息的基础操作后,进一步掌握更高级的SQL查询语句和优化策略将有助于提升数据管理与分析效率。近期,MySQL 8.0版本推出了一系列新特性,如窗口函数、JSON字段支持全文检索等,使得复杂查询与大数据处理更为便捷(来源:MySQL官网,2022年更新公告)。同时,随着云服务的普及,AWS RDS for MySQL、阿里云RDS等托管数据库服务提供了自动备份、性能监控、一键扩展等功能,极大地简化了MySQL的运维工作。 此外,对于表结构设计及索引优化的理解至关重要。一篇来自DBA Stack Exchange社区的热门讨论帖(发布日期:2022年5月)深入剖析了如何根据业务场景合理设计表关系,以及何时应创建唯一索引、复合索引以提高查询性能。而一篇发表于InfoQ的技术文章《MySQL性能调优实战》则从实战角度出发,详细解读了如何通过EXPLAIN分析查询执行计划、利用慢查询日志定位瓶颈,并结合实例探讨了分区表、分库分表策略在高并发场景下的应用。 综上所述,无论是紧跟MySQL最新技术动态,还是深化对数据库内部机制和性能优化的理解,都将为您的数据库管理工作带来显著提升。持续学习并实践这些进阶知识,能够帮助您更好地应对日益增长的数据管理和分析挑战。
2023-08-18 09:15:20
62
算法侠
MySQL
在深入理解MySQL数据库管理系统及其插入数据语句的基础上,我们可以进一步探索关系型数据库技术的最新发展动态和最佳实践。近日,Oracle公司发布了MySQL 8.0版本的重要更新,引入了一系列性能改进和新特性,如窗口函数支持、原子DDL操作以及安全性增强等,使得MySQL在处理大数据量及复杂查询场景时表现更为出色(来源:Oracle官网新闻发布,2023年)。 此外,随着云原生时代的到来,MySQL也在适应这一趋势,各大云服务提供商如AWS、阿里云等都提供了托管版MySQL服务,用户可以便捷地部署和管理MySQL数据库,同时享受到自动备份、高可用性和弹性扩展等高级功能。例如,AWS RDS for MySQL不仅简化了数据库管理任务,还通过读副本、多可用区部署等功能确保了数据的安全与高可用性(来源:AWS官方文档,2023年)。 在实际应用层面,对于Web开发者而言,掌握如何优化MySQL插入语句以提升数据写入效率至关重要。一篇来自Stack Overflow的深度讨论中,专家们就如何避免全表锁定、利用批量插入提高性能等问题进行了详细解读,并分享了一些实战经验(来源:Stack Overflow,2023年)。通过学习这些最新的技术资讯和发展趋势,可以帮助开发者更好地应对实际开发中的挑战,最大化发挥MySQL数据库的优势,从而为构建高效稳定的应用程序提供强大支撑。
2023-09-26 10:25:10
67
编程狂人
MySQL
...了如何查看和安装MySQL之后,进一步探讨MySQL的最新发展动态和技术应用。近期,MySQL 8.0版本持续更新,带来了性能优化、安全增强以及诸多新特性,如窗口函数支持更全面、JSON功能增强以及默认事务隔离级别的变更等。这对于开发者而言意味着更强大的数据处理能力和更丰富的开发选项。 另外,随着云服务的普及,各大云服务商如AWS、阿里云、腾讯云等均提供MySQL数据库托管服务,用户无需在本地安装,即可轻松部署和管理MySQL实例,极大地降低了运维难度和成本。例如,AWS RDS MySQL提供了自动备份、故障切换、读副本等功能,帮助企业实现数据库的高可用与扩展性。 此外,对于MySQL的学习者来说,社区资源与教程也不断推陈出新。诸如“MySQL 8.0从入门到精通”、“实战MySQL:高性能SQL优化、架构及集群”的在线课程和书籍,帮助初学者快速上手,并为有经验的开发者深入解析MySQL的内核机制和最佳实践。 综上所述,在MySQL的实际应用中,不仅应关注其安装配置,更要紧贴技术发展趋势,掌握最新的产品特性以提升数据库系统的性能与安全性,并结合云服务优势进行高效便捷的数据库管理与维护。同时,持续学习和跟进MySQL相关的教育资源,有助于不断提升自身技术水平,适应日益复杂多变的应用场景需求。
2023-09-19 12:58:09
133
算法侠
MySQL
在深入了解MySQL的常规连接与SSH连接后,我们可以进一步探索数据库安全和远程访问的最新技术和实践。近年来,随着云计算和大数据的发展,数据安全性问题日益凸显,如何确保数据库连接的安全性成为业界关注焦点。 2023年,MySQL官方发布了新版本,强化了SSL加密连接功能,用户可以设置强制使用SSL连接到MySQL服务器,以保护数据传输过程中不被窃取或篡改。此外,一些云服务提供商如阿里云、AWS等也提供了基于VPC(虚拟私有云)环境下的MySQL数据库连接方案,通过私有网络和子网策略增强数据库连接的安全层级。 另一方面,针对SSH隧道技术,开发者们正在研究如何优化其性能并提高可用性。例如,通过跳板机设置减少网络延迟,或者结合密钥对认证代替密码验证以提升安全性。同时,DevOps领域也在积极倡导采用自动化工具(如Ansible、Terraform)来配置和管理SSH隧道及MySQL连接,以实现更加高效和安全的运维流程。 此外,随着Kubernetes和Docker容器化技术的广泛应用,为MySQL数据库提供安全连接的方式也在发生变革。例如,利用Kubernetes中的Ingress资源,可实现从外部网络到集群内MySQL服务的安全访问,并且支持自动化的SSL证书管理和轮换。 总的来说,在关系型数据库管理系统中,MySQL连接方式的演进与发展,始终紧跟时代步伐,不断融入最新的安全理念和技术手段,以适应日益复杂的数据安全需求。对于技术人员而言,持续关注这些领域的动态和实践,无疑将有助于提升自身在数据库安全管理方面的专业素养和实战能力。
2023-06-22 12:09:56
134
码农
JSON
... 近期,业界对于如何优化这一过程展开了深入研究和实践应用。例如,2023年春季,Google Cloud推出了一款名为“Dataflow for JSON”的服务,该服务能够自动解析复杂JSON结构,并智能映射到BigQuery等云数据库中,极大地简化了JSON至关系型数据库的转换流程,提升了数据集成效率。 同时,一些开源项目也在积极探索这一领域,如PostgreSQL的jsonb数据类型就支持直接存储JSON并进行高效的查询操作,使得JSON数据可以直接在数据库层面进行深度处理,无需预先转换成传统的表结构。 此外,针对嵌套层级较深或动态结构变化频繁的JSON数据,有学者提出了基于NoSQL数据库的解决方案,如MongoDB的文档模型能很好地适应JSON数据的特性,实现灵活且高性能的数据管理。 总的来说,随着技术的发展和应用场景的变化,JSON数据转换为数据库表格式的方法不断演进,无论是通过增强传统关系型数据库的功能,还是借助NoSQL数据库的优势,都在推动着更高效、便捷的数据处理方式的创新与发展。
2023-11-04 08:47:08
443
算法侠
MySQL
在理解了MySQL中创建表的基本语法和关键要素后,我们可以进一步探讨数据库设计的实战应用以及最新技术动态。近期,随着MySQL 8.0版本的发布,对InnoDB存储引擎进行了多项性能优化和功能增强,例如提高了并发性、支持窗口函数等,使得在创建新表时,开发者可以充分利用这些新特性提升数据处理效率。 此外,对于表结构设计与字段选择的实际案例分析也尤为重要。例如,在构建电商系统时,用户订单表的设计可能不仅包括用户ID、商品ID等基础信息,还会涉及交易状态、下单时间等业务逻辑相关的字段,并且为了保证数据一致性,主键设计通常采用复合主键或者UUID以应对高并发场景下的自增主键冲突问题。 另外,关于字符集的选择,虽然UTF8仍然是广泛应用的标准,但随着全球化的深入发展,对于包含更多特殊字符或 emoji 的应用场景,MySQL 8.0 版本还引入了utf8mb4字符集的支持,能够存储更多的Unicode字符,确保更全面的语言兼容性。 同时,数据库设计中的注释规范也不容忽视,良好的注释不仅可以方便团队成员间的协作沟通,还能为后续的数据库维护、数据分析提供清晰的上下文信息。在实际工作中,建议遵循一定的数据库注释标准,如使用统一的注释格式,详细描述列的作用、数据来源及更新规则等,提高数据库的整体可读性和管理效率。 总之,MySQL建表只是数据库设计与管理的第一步,深入学习和掌握如何根据业务需求合理设计表结构、选择合适的数据类型及存储引擎,关注数据库技术的发展趋势,将有助于我们更好地构建高效、稳定、易于维护的数据库系统。
2023-10-30 22:22:20
117
码农
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
fg %jobnumber
- 将后台作业切换至前台运行。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"