前端技术
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
[INSERT OVERWRITE语句的高...]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
Mongo
...据库性能测试工具无法使用时的应对策略与实践 1. 引言 在我们的日常开发工作中,MongoDB作为一款高性能、易扩展的NoSQL数据库,其性能优化的重要性不言而喻。进行MongoDB的性能测试,就好比给系统的稳定运行上了保险锁,这可是至关重要的一步。不过呢,有时候咱们也会碰上些小插曲,比如性能测试工具突然罢工了,或者干脆耍赖不干活儿,这时候就有点尴尬啦。这篇文章打算手把手地带大家,通过实实在在的代码实例和接地气的探讨方式,让大家明白在这样的情况下,如何照样把MongoDB的性能测试和调优工作做得溜溜的。 2. MongoDB性能测试工具概述 通常,我们会利用如mongo-perf、JMeter、YCSB(Yahoo! Cloud Serving Benchmark)等专业工具对MongoDB进行压力测试和性能评估。然而,要是这些工具突然闹脾气,因为版本不兼容啦、配置没整对地儿啊,或者干脆是软件自带的小bug在作祟,没法正常干活了,我们该怎么办呢?这时候啊,就得让我们回归原始,用上MongoDB自家提供的命令行工具和编程接口,亲手摸一摸,测一测,才能找到问题的症结所在。 3. 手动性能测试实战 案例一:基于mongo shell的基本操作 javascript // 假设我们有一个名为"users"的集合,下面是一个插入大量数据的例子: for (var i = 0; i < 10000; i++) { db.users.insert({name: 'User' + i, email: 'user' + i + '@example.com'}); } // 对于读取性能的测试,我们可以计时查询所有用户: var start = new Date(); db.users.find().toArray(); var end = new Date(); print('查询用时:', end - start, '毫秒'); 案例二:使用Bulk Operations提升写入性能 javascript // 使用bulk operations批量插入数据以提高效率 var bulk = db.users.initializeUnorderedBulkOp(); for (var i = 0; i < 10000; i++) { bulk.insert({name: 'User' + i, email: 'user' + i + '@example.com'}); } bulk.execute(); // 同样,也可以通过计时来评估批量插入的性能 var startTime = new Date(); // 上述批量插入操作... var endTime = new Date(); print('批量插入用时:', endTime - startTime, '毫秒'); 4. 性能瓶颈分析与调优探讨 手动性能测试虽然原始,但却能够更直观地让我们了解MongoDB在实际操作中的表现。比如,通过瞅瞅插入数据和查询的速度,咱们就能大概摸清楚,是不是存在索引不够用、内存分配不太合理,或者是磁盘读写速度成了瓶颈这些小状况。在此基础上,我们可以针对性地调整索引策略、优化查询语句、合理分配硬件资源等。 5. 结论与思考 当标准性能测试工具失效时,我们应充分利用MongoDB内置的功能和API进行自定义测试,这不仅能锻炼我们深入理解数据库底层运作机制的能力,也能在一定程度上确保系统的稳定性与高效性。同时呢,这也告诉我们,在日常的开发工作中,千万不能忽视各种工具的使用场合和它们各自的“软肋”,只有这样,才能在关键时刻眼疾手快,灵活应对,迅速找到那个最完美的解决方案! 在未来的实践中,希望大家都能积极面对挑战,正如MongoDB性能测试工具暂时失效的情况一样,始终保持敏锐的洞察力和探索精神,让技术服务于业务,真正实现数据库性能优化的目标。
2023-01-05 13:16:09
135
百转千回
转载文章
...分析,屏蔽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
转载
DorisDB
...isDB中,我们可以使用流式API实现实时数据更新。首先,我们需要创建一个实时流表,然后通过流式API将数据发送到这个表中。例如,我们可以通过以下代码创建一个实时流表: sql CREATE TABLE my_table (id INT, value STRING) WITH ( 'stream.storage_format' = 'row', 'stream.is_realtime' = true ); 然后,我们可以通过以下代码将数据发送到这个表中: python from doris import Client client = Client(':') data = {'id': 1, 'value': 'Hello, World!'} client.insert('my_table', data) 三、如何实现数据增量更新? 在DorisDB中,我们可以使用 INSERT OVERWRITE 或者 UPDATE语句来实现数据增量更新。INSERT OVERWRITE语句会先删除已有数据,然后再插入新的数据,而UPDATE语句则会直接修改已有数据。 例如,我们有一个用户登录记录表,我们可以使用以下代码将最新的登录记录插入到表中: python data = {'user_id': 123, 'login_time': '2022-01-01 12:00:00'} client.insert_overwrite('user_login_records', data) 如果我们想修改某一条记录的数据,我们可以使用以下代码: python data = {'user_id': 123, 'login_time': '2022-01-01 12:00:00'} client.update('user_login_records', where='user_id=123', update=data) 四、总结 总的来说,DorisDB提供了丰富的数据更新和增量更新机制,可以帮助我们更好地管理和分析数据。无论是实时数据更新还是增量数据更新,都可以通过DorisDB的流式API和SQL语句轻松实现。大家伙儿,我真心希望你们能从这篇文章中摸清DorisDB的数据更新还有增量更新是怎么一回事儿,然后在你们自己的项目里头,像变魔术一样灵活运用起来,让数据更新变得so easy!谢谢大家!
2023-11-20 21:12:15
402
彩虹之上-t
转载文章
...务器读取配置文件,请使用启动选项“——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
转载
JSON
...SON数据:我们可以使用各种编程语言提供的JSON解读器来解读JSON数据,将其转化成数据结构。 将数据结构添加数据库表:最后,我们可以使用SQL语句将数据结构添加数据库表中。 -- 创建数据库表 CREATE TABLE users ( id INT PRIMARY KEY, name VARCHAR(50), email VARCHAR(50), address VARCHAR(100) ); -- 解读JSON数据 var data = JSON.parse('[ { "id": 1, "name": "Alice", "email": "alice@example.com", "address": { "street": "123 Main St", "city": "Anytown", "state": "USA", "zipcode": "12345" } }, { "id": 2, "name": "Bob", "email": "bob@example.com", "address": { "street": "456 High St", "city": "Anytown", "state": "USA", "zipcode": "67890" } } ]'); -- 将数据结构添加数据库表 for(var i = 0; i< data.length; i++) { var user = data[i]; var query = "INSERT INTO users (id, name, email, address) VALUES (?, ?, ?, ?)"; db.query(query, [user.id, user.name, user.email, JSON.stringify(user.address)]); } 在上述代码中,我们使用了JavaScript语言进行示例展示,但是相应的处理在其他编程语言,例如Python、Java、PHP等,也有相应的实现方法。总的来说,将JSON数据转化成表格形式,可以方便地对数据进行增删改查等处理,提高数据的处理速度和数据管控的便捷性。
2023-11-04 08:47:08
443
算法侠
MySQL
...表格形式存储数据,并使用结构化查询语言(SQL)进行交互的软件系统。在MySQL中,这种系统将数据组织成一系列相互关联的表格,通过预定义的关系或键来建立这些表格之间的联系,确保数据的一致性和完整性。用户可以通过执行SQL语句对数据进行增删改查等操作。 主键 , 在MySQL的表格设计中,主键是一个或一组列,其值能够唯一标识表中的每一行记录。例如,在上述customers表格中,id字段被定义为主键,它具有自动递增属性,这意味着每当新增一行记录时,系统会自动为该字段赋予一个唯一的、大于已有记录的数值,从而保证了每条客户记录的唯一性。 自动递增 , 自动递增是MySQL中主键的一种特殊属性。当某个字段被标记为自动递增(AUTO_INCREMENT),在插入新记录时不需手动指定该字段的值,MySQL会自动为该字段分配下一个可用的唯一整数值。比如在创建customers表格时,id字段设置为自动递增,每次插入新客户信息时,系统会自动为新记录分配一个比现有记录更大的id值,确保了主键字段的唯一性和连续性。 INSERT INTO 语句 , 在MySQL中,INSERT INTO 是用于向表格中添加新记录的关键SQL语句。它允许用户指定要插入数据的表格名称以及相应的列名和对应值。例如,INSERT INTO customers (first_name, last_name, email, age) VALUES ( John , Doe , john@example.com , 30 )这条语句会在customers表格中插入一条包含姓名、电子邮件和年龄的新客户记录。 SELECT 语句 , SELECT 是MySQL中用于从数据库表格中检索数据的核心SQL命令。通过编写不同的SELECT语句,可以实现对表格中数据的不同筛选、排序和组合需求。如 SELECT FROM customers; 这条语句表示从customers表格中选择所有列的所有记录,返回整个表格的内容。 DROP TABLE 语句 , 在MySQL中,DROP TABLE 是一种DDL(数据定义语言)命令,用于删除不再需要的数据库表格及其所有相关数据。例如,执行 DROP TABLE customers; 将永久删除名为customers的表格,包括其中的所有客户记录,这个操作不可逆,所以在执行前应确保已备份重要数据或确实不需要该表格。
2023-01-01 19:53:47
73
代码侠
MySQL
...MySQL是一种广泛使用的关系型数据库管理系统,由Oracle公司开发并维护。在本文中,MySQL用于存储和管理结构化数据,通过SQL(Structured Query Language)语句进行数据的增删改查等操作。用户可以创建多个数据库并在其中定义不同的表结构,以满足不同应用场景的需求。 关系型数据库 , 关系型数据库是基于关系模型理论设计的数据库,其数据以表格的形式存储,并通过预定义的数据关系进行组织和关联。在MySQL中,每张表都有特定的列(字段),用来描述记录(行)的属性;同时,表与表之间可以通过键(如主键和外键)建立联系,实现数据的一致性和完整性。 mysqli_connect函数 , 在PHP编程语言中,mysqli_connect是一个内置函数,用于连接到MySQL服务器并打开一个数据库连接。该函数接收四个参数,分别是MySQL服务器的地址、数据库用户名、密码以及要连接的数据库名。成功连接后返回一个连接标识符,后续的SQL查询和数据操作都将通过这个连接标识符进行,如在文章中提到的执行查询、插入数据等任务。 INSERT INTO语句 , INSERT INTO是SQL语言中的命令,用于向指定的数据库表中插入新的数据行。在文中,INSERT INTO customers (name, email, phone) VALUES ( John Doe , johndoe@example.com , 555-555-5555 ) 这条语句将一条包含姓名、电子邮箱和电话号码的新客户记录添加到了名为“customers”的表中。每个括号内的字段名对应值后面的变量,确保数据被正确地插入到相应字段内。 mysqli_query函数 , 在PHP的MySQLi扩展中,mysqli_query函数用于执行一个SQL查询或命令。它可以处理SELECT、INSERT、UPDATE、DELETE等多种类型的SQL语句,并根据查询类型返回结果集或影响行数。在本文上下文中,mysqli_query函数不仅用于从“customers”表中选择所有记录,还用于执行INSERT INTO语句以插入新数据,并在插入后再次查询渲染新添加的数据。
2024-02-04 16:16:22
70
键盘勇士
转载文章
...----------INSERT INTO com_area VALUES ('1', '2016-10-29 08:07:39', '2016-10-29 08:07:39', '0', '1', null);INSERT INTO com_area VALUES ('2', '2016-10-29 08:07:44', '2016-10-29 08:07:44', '110000', '北京市', '1');INSERT INTO com_area VALUES ('3', '2016-10-29 08:07:44', '2016-10-29 08:07:44', '110101', '东城区', '2');...... 下载地址: http://download.csdn.net/detail/wangfei0904306/9748322 本篇文章为转载内容。原文链接:https://blog.csdn.net/wangfei0904306/article/details/54895475。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-06-30 09:11:08
62
转载
Greenplum
...reenplum查询语句中出现的数据类型转换错误。 二、问题描述 当我们尝试将一个数据类型转换为另一个数据类型时,如果这个转换在逻辑上是不正确的,那么就会出现数据类型转换错误。比如,假如你正试着把一个字符串变成整数,可这个字符串里头混进了非数字的字符,那这就肯定会出错啦。 三、示例 下面是一个简单的例子,展示了在Greenplum中如何发生数据类型转换错误: sql CREATE TABLE test_table (id int, name text); INSERT INTO test_table VALUES (1, 'test'); SELECT id::text FROM test_table; -- 这将会报错 在这个例子中,我们试图将id列从整数类型转换为文本类型。不过,你看哈,这id列里头存的都是些整数,比如1啊这些。所以呢,这个转换操作就有点儿跑偏了,自然而然地,这就引发了错误啦。 四、解决方案 要解决这种问题,我们需要确保我们的数据类型转换是正确的。这可能意味着我们需要先给咱们的数据“整整容”,或者调整一下我们的查询方式,让它更贴近我们想要的结果。 例如,在上面的例子中,我们可以先将id列转换为文本类型,然后再将其插入到测试表中: sql CREATE TABLE test_table (id text, name text); INSERT INTO test_table SELECT cast(id AS text), name FROM test_table; SELECT FROM test_table; 这样就可以避免数据类型转换错误了。 五、总结 在处理数据类型转换时,我们必须非常小心,因为错误的数据类型转换会导致各种各样的问题。幸运的是,只要我们对这些小细节多上点心,及时采取一些适当的预防措施,就能轻松把这些问题扼杀在摇篮里,让它们没机会冒头。 总的来说,虽然数据类型转换可能会带来一些挑战,但只要我们了解并正确地使用它们,我们就能够充分利用Greenplum和其他数据库系统的强大功能。
2023-11-08 08:41:06
598
彩虹之上-t
DorisDB
...越复杂,为了满足不同场景下的需求,数据库系统也不断地发展和升级。DorisDB是一款大家都在用的开放源代码列式数据库系统,不仅在速度和处理能力上表现得超级给力,还能轻松实现数据的实时查询和深度分析,实用性超强!这篇内容,咱要重点聊聊怎么在DorisDB里头给用户设置权限,这样一来,咱们就能把那些敏感数据的安全性保护得更上一层楼啦! 二、DorisDB中的用户权限管理 在DorisDB中,用户权限主要分为三个级别:用户、角色和权限。在咱们这里,所谓的“用户”,其实就是指那些手握DorisDB账号、能够登录的亲们;而“角色”呢,就好比是一个小团队,这个团队里的成员都拥有同样的权限级别;至于“权限”,简单来说就是用户在系统里能干啥、能操作哪些东东的一个界定。这三个级别的关系如下图所示:  下面我们将详细介绍一下如何在DorisDB中设置这三种类型的用户权限。 1. 用户权限设置 首先,我们需要创建一个用户并设置其密码。可以通过以下命令来创建一个名为test_user的用户: sql CREATE USER test_user WITH PASSWORD 'test_password'; 然后,我们可以使用以下命令来授予用户特定的权限: sql GRANT SELECT ON TABLE my_table TO test_user; 上述命令表示授予用户test_user在my_table表上进行SELECT操作的权限。 我们还可以使用以下命令来查看用户的权限情况: sql SHOW GRANTS FOR test_user; 以上就是如何设置用户权限的基本步骤。 2. 角色权限设置 在DorisDB中,我们通常会创建一些角色,并将多个用户分配给同一个角色,这样可以方便地管理用户权限。以下是创建角色和分配用户的示例: sql CREATE ROLE admin; CREATE USER user1 WITH PASSWORD 'password1' IDENTIFIED BY 'user1'; SET ROLE admin; GRANT ALL PRIVILEGES ON DATABASE default TO user1; SET ROLE NONE; 上述命令首先创建了一个名为admin的角色,然后创建了一个名为user1的用户,并将其分配给了admin角色。最后,我们将用户user1授权为默认数据库的所有者。 要查看用户分配的角色,请使用以下命令: sql SHOW ROLES; 如果要查看某个角色拥有的所有权限,请使用以下命令: sql SHOW GRANTS FOR ROLE admin; 3. 权限管理 在DorisDB中,我们可以使用GRANT和REVOKE语句来管理和控制用户的权限。例如,如果我们想要撤销用户user1在my_table上的SELECT权限,可以使用以下命令: sql REVOKE SELECT ON TABLE my_table FROM user1; 同样,我们也可以使用GRANT语句来授予用户新的权限。例如,如果我们想要授予用户user1在my_table上的INSERT权限,可以使用以下命令: sql GRANT INSERT ON TABLE my_table TO user1; 4. 安全设置 在DorisDB中,除了管理用户权限之外,还需要注意安全设置。比如,我们可以用ENCRYPTED PASSWORD这个小功能,给用户的密码加上一层保护壳,这样一来,安全性就大大提升了,就像是给密码穿了件防弹衣一样。此外,我们还可以使用防火墙等工具来限制对DorisDB的访问。 总的来说,DorisDB提供了一套强大的用户权限管理系统,可以帮助我们有效地管理和保护数据安全。希望本文能对你有所帮助!
2024-01-22 13:14:46
454
春暖花开-t
MyBatis
...是将一个复杂的SQL语句映射为一个简单的Java方法,然后由MyBatis框架去执行这个SQL语句,并返回结果集。 在MyBatis中,我们可以使用两种方式来定义SQL映射:XML文件和注解。在这篇文章中,我们将主要讨论如何使用注解来实现SQL映射。 三、MyBatis的注解使用 首先,我们需要在我们的类上添加一个@Mapper注解。这个东西啊,是个神奇的小标签,它的作用是告诉大伙儿,这个类其实是个接口,并且呢,它还特别标注自己是一个Mapper类型的接口。就像是给这个接口戴了个“我是Mapper接口”的小帽子,让人一眼就能认出它的身份。 java @Mapper public interface UserMapper { // ... } 接下来,我们可以在我们的方法上添加一些注解来指定SQL语句。例如,我们可以使用@Select注解来指定查询语句。 java @Select("SELECT FROM user WHERE id = {id}") User selectUserById(int id); 在上面的例子中,{id}是一个占位符,它的值将在运行时从参数列表中获取。这使得我们可以灵活地改变SQL语句的内容。 除了@Select注解,MyBatis还提供了其他的注解,如@Insert、@Update、@Delete等,分别用于执行插入、更新和删除操作。 java @Insert("INSERT INTO user (name, age) VALUES ({name}, {age})") void insertUser(User user); 以上就是MyBatis使用注解实现SQL映射的基本步骤。当然啦,还有很多牛逼哄哄的高级功能,比如动态SQL、延迟加载这些小玩意儿,在我们日常使用的过程中,会不断地摸索和学习,让它们为我们所用。 四、总结 总的来说,使用MyBatis的注解方式实现SQL映射是一种非常方便、高效的方式。它不仅可以让我们的代码更加简洁,而且还能提高开发效率。我相信,在未来的开发中,MyBatis将会发挥更大的作用。 最后,我想说的是,虽然MyBatis可以帮助我们解决很多问题,但我们也需要不断地学习和探索,以便更好地利用它。毕竟,技术是一把双刃剑,掌握得好,就能给我们带来无穷的力量。
2023-01-16 14:18:50
176
笑傲江湖-t
c#
...tatic int Insert(string tableName, Dictionary values) { string columns = String.Join(",", values.Keys); string parameters = String.Join(",", values.Keys.Select(k => "@" + k)); string sql = $"INSERT INTO {tableName} ({columns}) VALUES ({parameters})"; using (SqlCommand cmd = new SqlCommand(sql, connection)) { foreach (var pair in values) { cmd.Parameters.AddWithValue("@" + pair.Key, pair.Value); } return cmd.ExecuteNonQuery(); } } } 上述代码中,我们尝试构建一个动态SQL语句来插入数据。但在实际使用过程中,可能会出现如下问题: - SQL注入风险:由于直接拼接用户输入的数据生成SQL语句,存在SQL注入的安全隐患。 - 类型转换异常:AddWithValue方法可能因为参数值与数据库列类型不匹配而导致类型转换错误。 - 空值处理不当:当字典中的某个键值对的值为null时,可能导致插入失败或结果不符合预期。 3. 解决方案与优化策略 3.1 防止SQL注入 为了避免SQL注入,我们可以使用参数化查询,确保即使用户输入包含恶意SQL片段,也不会影响到最终执行的SQL语句: csharp string sql = "INSERT INTO {0} ({1}) VALUES ({2})"; sql = string.Format(sql, tableName, string.Join(",", values.Keys), string.Join(",", values.Keys.Select(k => "@" + k))); using (SqlCommand cmd = new SqlCommand(sql, connection)) { // ... } 3.2 明确指定参数类型 为了防止因类型转换导致的异常,我们应该明确指定参数类型: csharp foreach (var pair in values) { var param = cmd.CreateParameter(); param.ParameterName = "@" + pair.Key; param.Value = pair.Value ?? DBNull.Value; // 处理空值 // 根据数据库表结构,明确指定param.DbType cmd.Parameters.Add(param); } 3.3 空值处理 在向数据库插入数据时,对于可以接受NULL值的字段,我们应该将C中的null值转换为DBNull.Value: csharp param.Value = pair.Value ?? DBNull.Value; 4. 总结与思考 封装SqlHelper类确实大大提高了开发效率,但同时也要注意在实际应用中可能出现的各种问题。在我们往数据库里插数据的时候,可能会遇到一些捣蛋鬼,像是SQL注入啊、类型转换出岔子啊,还有空值处理这种让人头疼的问题。所以呢,咱们得采取一些应对策略和优化手段,把这些隐患通通扼杀在摇篮里。在实际编写代码的过程中,只有不断挠头琢磨、反复试验改进,才能让我们的工具箱越来越结实耐用,同时也更加得心应手,好用到飞起。 最后,尽管上述改进已极大地提升了安全性与稳定性,但我们仍需时刻关注数据库操作的最佳实践,如事务处理、并发控制等,以适应更为复杂的应用场景。毕竟,编程不仅仅是解决问题的过程,更是人类智慧和技术理解力不断提升的体现。
2024-01-17 13:56:45
538
草原牧歌_
转载文章
...CREMENT A、使用insert into插入数据时,若abc的值已存在,因其为唯一键,故不会插入成功。但此时,那个AUTO_INCREMENT已然+1了。 eg : insert into table set abc = '123' B、使用replace插入数据时,若abc的值已存在,则会先删除表中的那条记录,尔后插入新数据。 eg : replace into table set abc = '123' (注:上一行中的into可省略;这只是一种写法。) 这两种方法,效果都不好:A会造成id不连续,B会使得原来abc对应的id值发生改变,而这个id值会和其它表进行关联,这是更不允许的。 那么,有没有解决方案呢? 笨办法当然是有:每次插入前先查询,若表中不存在要插入的abc的值,才插入。 但这样,每次入库之前都会多一个操作,麻烦至极。 向同学请教,说用触发器。可在网上找了半天,总是有问题。可能是语法不对,或者是某些东西有限制。 其实,最终要做的,就是在每次插入数据之后,修正那个AUTO_INCREMENT值。 于是就想到,把这个最实质的SQL语句↓,合并在插入的SQL中。 PS: ALTER TABLE table AUTO_INCREMENT =1 执行之后,不一定再插入的id就是1;而是表中id最大值+1。 这是MySQL中的执行结果。其它数据库不清楚。。。。 到这里,问题就变的异常简单了:在每次插入之后都重置AUTO_INCREMENT的值。 如果插入的自定义函数或类的名称被定义成insert的话,那么就在此基础上扩展一个函数insert_continuous_id好了,其意为:保证自增主键连续的插入。 为什么不直接修改原函数呢? 这是因为,并不是所有的insert都需要修正AUTO_INCREMENT。只有在设置唯一键、且有自增主键时才有可能需要。 虽然重置不会有任何的副作用(经试验,对各种情况都无影响),但没有必要就不要额外增加这一步。 一个优秀的程序员,就是要尽量保证写出的每一个字符都有意义而不多余。 啰啰嗦嗦的说了这么多,其实只有一句话:解决MySQL中自增主键不连续的方法,就是上面PS下的那一行代码。 附: 我写的不成功的触发器的代码。 -- 触发器 CREATE TRIGGER trigger_table after insert ON table FOR EACH ROW ALTER TABLE table AUTO_INCREMENT =1; 大家有想说的,请踊跃发言。期待更好更完美的解决方案。 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_39554172/article/details/113210084。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-08-26 08:19:54
92
转载
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
月影清风
MyBatis
...之间的转换整得既溜又高效,这可真是个不容忽视的关键点。在这个章节里,我们将一起深入探讨MyBatis如何帮助我们解决这类问题。 二、MyBatis基础介绍 MyBatis 是一个优秀的 Java持久层框架,它将 SQL 语句与对象绑定起来,使得开发者无需关心底层数据库操作的繁琐细节。在查询结果处理这个环节,MyBatis特地提供了超级实用的和标签大法,就是为了帮我们轻松搞定基本的数据类型转换,还能无缝衔接处理一对一、一对多这种复杂的关系映射问题,让数据映射过程既简单又省心。但对于复杂的数据结构转换,例如 JSON,MyBatis本身并未直接支持,需要借助一些额外的技术手段。 三、实体类与JSON数据之间的映射 1. 使用第三方库——Jackson或Gson 对于实体类与JSON之间的转换,最常用的方法是借助诸如 Jackson 或 Gson 这样的 JSON 库。首先,在项目中引入相应的依赖: xml com.fasterxml.jackson.core jackson-databind 2.13.4 // 或者 Gson com.google.code.gson gson 2.9.1 接下来,为实体类定义一个对应的 toString() 方法,使其自动生成 JSON 字符串: java public class User { private String id; private String name; // getters and setters @Override public String toString() { return new Gson().toJson(this); } } 然后在 MyBatis 的 XML 映射文件中使用 语句,并设置其 resultType 为 String 类型,配合 toString() 方法即可得到 JSON 数据:xml SELECT FROM user WHERE id = {id} 通过这种方式,MyBatis 会调用用户自定义的 toString() 方法生成对应的 JSON 字符串。 2. 自定义类型处理器(TypeHandler) 然而,如果我们想要更灵活地控制数据转换过程,或者映射包含嵌套的对象结构,可以考虑自定义类型处理器。这里以 Jackson 为例,创建一个继承自 org.apache.ibatis.type.TypeHandler 的 UserToJsonTypeHandler 类: java import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.MappedTypes; @MappedTypes(User.class) public class UserToJsonTypeHandler extends BaseTypeHandler { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @Override public void setNonNullParameter(PreparedStatement ps, int i, User parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, OBJECT_MAPPER.writeValueAsString(parameter)); } @Override public User getNullableResult(ResultSet rs, String columnName) throws SQLException { String jsonString = rs.getString(columnName); return OBJECT_MAPPER.readValue(jsonString, User.class); } @Override public User getNullableResult(ResultSet rs, int columnIndex) throws SQLException { // ... (类似地处理其他获取方式) } @Override public User getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { // ... (类似地处理其他获取方式) } } 在配置文件中注册这个自定义类型处理器: xml INSERT INTO user (json_data) VALUES (?) SELECT json_data FROM user WHERE id = {id} 现在,User 对象可以直接插入和查询为 JSON 字符串形式,而不需要手动调用 toString() 方法。 四、总结与讨论 通过本篇文章的学习,我们可以了解到 MyBatis 在默认情况下并不直接支持实体类与 JSON 数据的自动转换。不过,要是我们借助一些好用的第三方JSON工具,比如Jackson或者Gson,再配上自定义的类型处理器,就能超级灵活、高效地搞定这种复杂的数据映射难题啦,就像变魔术一样神奇!在我们实际做开发的时候,就得瞅准业务需求,挑那个最对味的解决方案来用。而且啊,你可别忘了把 MyBatis 的其他功能也玩得溜溜转,这样一来,你的应用性能就能噌噌往上涨,开发效率也能像火箭升空一样蹭蹭提升。同时呢,掌握并实际运用这些小技巧,也能让你在面对其他各种复杂场景下的数据处理难题时,更加游刃有余,轻松应对。
2024-02-19 11:00:31
75
海阔天空-t
ClickHouse
...手,踏上这场探寻数据高效流转的奇妙之旅吧! 1. 引言 为何选择ClickHouse? 首先,让我们理解一下为什么众多企业会选择ClickHouse进行大规模数据分析。ClickHouse这玩意儿,厉害的地方在于它采用了列式存储技术,配上那酷炫的向量化执行引擎,再加上对分布式计算的强力支持,能够轻轻松松地在短短一秒内处理完PB级别的海量数据查询,速度快得飞起!对于实时数据分析、日志分析等场景,它无疑是一个理想的工具。因此,熟练掌握ClickHouse的数据导入与导出技巧至关重要。 2. 数据导入到ClickHouse的最佳实践 2.1 使用INSERT INTO语句导入数据 ClickHouse提供了直接插入数据的方式,例如: sql INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2') 但面对大量数据时,我们通常采用批量插入的方式以提升效率: sql INSERT INTO table_name FORMAT CSV /path/to/data.csv 这里,CSV是文件格式,ClickHouse还支持JSONEachRow、TabSeparated等多种格式。 2.2 利用clickhouse-client命令行工具导入数据 通过命令行工具可以方便地将本地数据导入到ClickHouse服务器: bash cat /path/to/large_data.csv | clickhouse-client --query="INSERT INTO table_name FORMAT CSV" 2.3 使用clickhouse-local进行快速导入 对于超大型数据集,clickhouse-local可以在本地完成数据预处理并一次性导入到数据库,大大减少网络传输带来的延迟: bash clickhouse-local --structure "column1 String, column2 Int32" --input-format "CSV" --output-format "Native" --query "INSERT INTO table_name" < large_data.csv 3. 数据从ClickHouse导出的最佳实践 3.1 使用SELECT INTO OUTFILE导出数据 你可使用SQL查询配合INTO OUTFILE导出数据至本地文件: sql SELECT FROM table_name INTO OUTFILE '/path/to/exported_data.csv' FORMAT CSV 3.2 利用clickhouse-client导出数据 同样,我们可以通过客户端工具将查询结果直接输出到终端或重定向到文件: bash clickhouse-client -q "SELECT FROM table_name" > exported_data.csv 3.3 配合其他工具实现定时增量导出 为了满足持续性监控或ETL需求,我们可以结合cron作业或其他调度工具,定期执行导出操作,确保数据的时效性和完整性。 4. 总结与思考 ClickHouse强大的数据处理能力不仅体现在查询速度上,也体现在灵活且高效的数据导入导出功能。在实际操作中,咱们得瞅准业务的具体需求,挑个最对路的导入导出方法。而且呀,这可不是一劳永逸的事儿,咱还要随时调整、持续优化这个流程,好让数据量越来越大时,也能应对自如,不至于被挑战压垮了阵脚。同时,千万要记住,在这个过程中,摸清楚数据的脾性和应用场景,灵活机动地调整策略,这才是真正让ClickHouse大显身手的秘诀!每一次数据流动的背后,都承载着我们的深度思考和细致打磨,而这正是数据工程师们在实战中磨砺成长的过程。
2023-02-14 13:25:00
491
笑傲江湖
Impala
使用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
月下独酌
Cassandra
... Language)语句,从而显著提高数据插入和更新效率,节省网络开销,并保持数据库的一致性。 2. 理解Cassandra Batch操作 (1)什么是Batch? 在Cassandra中,Batch主要用于将多个CQL语句捆绑在一起执行。想象一下,你正在为一个大型电商系统处理订单,需要同时在不同的表中插入或更新多条记录,这时候Batch就派上用场了。使用Batch操作,你就能像一次性打包处理那样,让这些操作要么全盘搞定,要么一个也不动,就像“要干就干到底,不干就拉倒”的那种感觉,确保了操作的完整性。 cql BEGIN BATCH INSERT INTO orders (order_id, customer_id, product) VALUES (1, 'user1', 'productA'); INSERT INTO order_details (order_id, detail_id, quantity) VALUES (1, 1001, 2); APPLY BATCH; (2)Batch操作的注意事项 虽然Batch操作在提高性能方面有显著效果,但并非所有情况都适合使用。Cassandra对Batch大小有限制(默认约16MB),过大的Batch可能导致性能下降甚至错误。另外,你知道吗,Cassandra这个数据库啊,它属于AP型的,所以在批量操作这块儿,就不能给你提供像传统数据库那样的严格的事务保证啦。它更倾向于保证“原子性”,也就是说,一个操作要么全完成,要么全不完成,而不是追求那种所有的数据都得在同一时刻保持完全一致的“一致性”。 3. Cassandra的数据批量加载 (1)SSTableLoader工具 当我们面对海量历史数据迁移或初始化大量预生成数据时,直接通过CQL进行批量插入可能并不高效。此时,Cassandra提供的sstableloader工具可以实现大批量数据的快速导入。这个工具允许我们将预先生成好的SSTable文件直接加载到集群中,极大地提高了数据加载速度。 bash bin/sstableloader -u -p -d /path/to/sstables/ (2)Bulk Insert与COPY命令 对于临时性的大量数据插入,也可以利用CQL的COPY命令从CSV文件中导入数据,或者编写程序进行Bulk Insert。这种方式虽然不如sstableloader高效,但在灵活性上有一定优势。 cql COPY orders FROM '/path/to/orders.csv'; 或者编程实现Bulk Insert: java Session session = cluster.connect("my_keyspace"); PreparedStatement ps = session.prepare("INSERT INTO orders (order_id, customer_id, product) VALUES (?, ?, ?)"); for (Order order : ordersList) { BoundStatement bs = ps.bind(order.getId(), order.getCustomerId(), order.getProduct()); session.execute(bs); } 4. 深入探讨与实践总结 尽管Cassandra的Batch操作和批量加载功能强大,但运用时需要根据实际业务场景灵活调整策略。比如,在网络比较繁忙、负载较高的时候,咱就得避免一股脑地进行大批量的操作。这时候,咱们可以灵活调整批次的大小,就像在平衡木上保持稳定一样,既要保证性能不打折,又要让网络负载不至于过大,两头都得兼顾好。此外,说到批量加载数据这事儿,咱们得根据实际情况,灵活选择最合适的方法。比如说,你琢磨一下是否对实时性有要求啊,数据的格式又是个啥样的,这些都是决定咱采用哪种方法的重要因素。 总之,无论是日常开发还是运维过程中,理解和掌握Cassandra的Batch操作及批量加载技术,不仅能提升系统的整体性能,还能有效应对复杂的大规模数据管理挑战。在实际操作中不断尝试、捣鼓,让Cassandra这个家伙更好地为我们业务需求鞍前马后地服务,这才是技术真正价值的体现啊!
2024-02-14 11:00:42
505
冬日暖阳
转载文章
...询出前5条,将SQL语句与执行结果截图粘贴至对应报告中; spark.sql("select nationkey,regexp_replace(nationname,'\'','') as nationname,regionkey,regexp_replace(regionname,'\'','') as regionname,sum(totalnum) as totalorder,sum(totalprice) as totalconsumption,year,month from nationeverymonth group by nationkey,regionkey,month,nationname,year,regionname;") 我为了方便查询和之后的操作,将上面的查询结果导入到新表nationeverymonths 查表 接下来将hive中的数据导入mysql中 package com.atguigu.spark.sqlimport org.apache.spark.SparkConfimport org.apache.spark.sql.SparkSessionimport java.util.Propertiesobject DataHiveToMySQL {def main(args: Array[String]): Unit = {val sparkConf = new SparkConf().setMaster("local[]").setAppName("sparkSQL")val spark = SparkSession.builder().enableHiveSupport().config(sparkConf).getOrCreate()val result=spark.sql("select from ods.nationeverymonths")val props=new Properties()props.setProperty("user","root")props.setProperty("password","123456")props.setProperty("driver","com.mysql.jdbc.Driver")result.write.mode("overwrite").jdbc("jdbc:mysql://192.168.230.132:3306/user?serverTimezone=UTC&characterEncoding=UTF-8&useSSL=false", "nationeverymonth", props)println("导入成功")spark.stop()} } 运行可见导入成功 进入MySQL中查看结果 可见数据成功导入 接下来按照要求查询: 2.请根据dwd层表计算出某年每个国家的平均消费额和所有国家平均消费额相比较结果(“高/低/相同”),存入MySQL数据库shtd_store的nationavgcmp表(表结构如下)中,然后在Linux的MySQL命令行中根据订单总数、消费总额、国家表主键三列均逆序排序的方式,查询出前5条,将SQL语句与执行结果截图粘贴至对应报告中; 在解这道题的时候遇见一个问题,在求所有国家平均消费额的时候一直报错,由于没有数据这道题的题意还是有点没看明白,于是我就用了最简单的办法先新增一列,再单独将所有国家平均消费额求出来然后再插入,如果各位大佬有解决这个问题的办法希望能指导一下 先将每个国家的平均消费额求出来 spark.sql("select nationkey,nationname,avg(totalconsumption) as nationavgconsumption from nationeverymonths group by nationkey,nationname") 再新增一列所有国家平均消费额 spark.sql("alter table nationeverymonths add columns(avg_allstring)") 再将查询到的所有国家平均消费额导入进去 spark.sql("insert overwrite table nationeverymonths1 select nationkey,nationname,avg_totalconsumpt,1500 from nationeverymonths1") 再次查表 按照题意添加比较结果字段 spark.sql("select ,case when avg_totalconsumpt>avg_all then '高' when avg_totalconsumpt<avg_all then '低' when avg_totalconsumpt=avg_all then '相同' else 'null' end as comparison from nationeverymonths1").show 最后的排序语句和题一一样 本篇文章为转载内容。原文链接:https://blog.csdn.net/guo_0423/article/details/126352162。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-09-01 10:55:33
319
转载
转载文章
..."> <insert id="save" parameterType="User"> insert into t_user(user_name,user_age) values({userName},{age}) </insert> <update id="update" parameterType="User"> update t_user set user_name={userName},user_age={age} where user_id={id} </update> <delete id="delete" parameterType="int"> delete from t_user where user_id={id} </delete> <!-- mybsits_config中配置的alias类别名,也可直接配置resultType为类路劲 --> <select id="findById" parameterType="int" resultType="User"> select user_id id,user_name userName,user_age age from t_user where user_id={id} </select> <select id="findAll" resultType="User"> select user_id id,user_name userName,user_age age from t_user </select> </mapper> 这里对这个xml文件作几点说明: 1、namespace必须与对应的接口全类名一致。 2、id必须与对应接口的某个对应的方法名一致即必须要和UserMapper.java接口中的方法同名。 第六步:Mybatis和Spring的整合 对于Mybatis和Spring的整合是这篇博文的重点,需要配置的内容在下面有详细的解释。 [html] view plaincopy print? <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 1. 数据源 : DriverManagerDataSource --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis" /> <property name="username" value="root" /> <property name="password" value="123456" /> </bean> <!-- 2. mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource:引用数据源 MyBatis定义数据源,同意加载配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:config/mybatis-config.xml" /> </bean> <!-- 3. mybatis自动扫描加载Sql映射文件/接口 : MapperScannerConfigurer sqlSessionFactory basePackage:指定sql映射文件/接口所在的包(自动扫描) --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.tgb.mapper"></property> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> <!-- 4. 事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 5. 使用声明式事务 transaction-manager:引用上面定义的事务管理器 --> <tx:annotation-driven transaction-manager="txManager" /> </beans> 第七步:mybatis的配置文件 [html] view plaincopy print? <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 实体类,简称 -设置别名 --> <typeAliases> <typeAlias alias="User" type="com.tgb.model.User" /> </typeAliases> <!-- 实体接口映射资源 --> <!-- 说明:如果xxMapper.xml配置文件放在和xxMapper.java统一目录下,mappers也可以省略,因为org.mybatis.spring.mapper.MapperFactoryBean默认会去查找与xxMapper.java相同目录和名称的xxMapper.xml --> <mappers> <mapper resource="com/tgb/mapper/userMapper.xml" /> </mappers> </configuration> 总结 Mybatis和Spring的集成相对而言还是很简单的,祝你成功。 源码下载:SpringMVC+Spring4+Mybatis3 下篇博文我们将Hibernate和Mybatis进行一下详细的对比。 本篇文章为转载内容。原文链接:https://blog.csdn.net/konglongaa/article/details/51706991。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-09-05 11:56:25
111
转载
转载文章
...开放源代码:(源协议使用宽松的“Mozilla Public License”许可,允许将开源代码与闭源代码混在一起使用。) 完全的ACID支持 可横向扩展的关系型数据库(RDBMS) 支持OLAP应用,采用MPP(Massively Parallel Processing:大规模并行处理系统)架构模式 支持OLTP应用,读写性能可扩展 集群级别的ACID特性 多租户安全 也可被用作分布式Key-Value存储 事务处理与数据分析处理混合型数据库 支持丰富的SQL语句类型,比如:关联子查询 支持绝大部分PostgreSQL的SQL语句 分布式多版本并发控制(MVCC:Multi-version Concurrency Control) 支持JSON和XML格式 Postgres-XL缺少的功能 内建的高可用机制 使用外部机制实现高可能,如:Corosync/Pacemaker 有未来功能提升的空间 增加节点/重新分片数据(re-shard)的简便性 数据重分布(redistribution)期间会锁表 可采用预分片(pre-shard)方式解决,在同台物理服务器上建立多个数据节点,每个节点存储一个数据分片。数据重分布时,将一些数据节点迁出即可 某些外键、唯一性约束功能 Postgres-XL架构 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-M9lFuEIP-1640133702200)(./assets/postgre-xl.jpg)] 基于开源项目Postgres-XC XL增加了MPP,允许数据节点间直接通讯,交换复杂跨节点关联查询相关数据信息,减少协调器负载。 多个协调器(Coordinator) 应用程序的数据库连入点 分析查询语句,生成执行计划 多个数据节点(DataNode) 实际的数据存储 数据自动打散分布到集群中各数据节点 本地执行查询 一个查询在所有相关节点上并行查询 全局事务管理器(GTM:Global Transaction Manager) 提供事务间一致性视图 部署GTM Proxy实例,以提高性能 Postgre-XL主要组件 GTM (Global Transaction Manager) - 全局事务管理器 GTM是Postgres-XL的一个关键组件,用于提供一致的事务管理和元组可见性控制。 GTM Standby GTM的备节点,在pgxc,pgxl中,GTM控制所有的全局事务分配,如果出现问题,就会导致整个集群不可用,为了增加可用性,增加该备用节点。当GTM出现问题时,GTM Standby可以升级为GTM,保证集群正常工作。 GTM-Proxy GTM需要与所有的Coordinators通信,为了降低压力,可以在每个Coordinator机器上部署一个GTM-Proxy。 Coordinator --协调器 协调器是应用程序到数据库的接口。它的作用类似于传统的PostgreSQL后台进程,但是协调器不存储任何实际数据。实际数据由数据节点存储。协调器接收SQL语句,根据需要获取全局事务Id和全局快照,确定涉及哪些数据节点,并要求它们执行(部分)语句。当向数据节点发出语句时,它与GXID和全局快照相关联,以便多版本并发控制(MVCC)属性扩展到集群范围。 Datanode --数据节点 用于实际存储数据。表可以分布在各个数据节点之间,也可以复制到所有数据节点。数据节点没有整个数据库的全局视图,它只负责本地存储的数据。接下来,协调器将检查传入语句,并制定子计划。然后,根据需要将这些数据连同GXID和全局快照一起传输到涉及的每个数据节点。数据节点可以在不同的会话中接收来自各个协调器的请求。但是,由于每个事务都是惟一标识的,并且与一致的(全局)快照相关联,所以每个数据节点都可以在其事务和快照上下文中正确执行。 Postgres-XL继承了PostgreSQL Postgres-XL是PostgreSQL的扩展并继承了其很多特性: 复杂查询 外键 触发器 视图 事务 MVCC(多版本控制) 此外,类似于PostgreSQL,用户可以通过多种方式扩展Postgres-XL,例如添加新的 数据类型 函数 操作 聚合函数 索引类型 过程语言 安装 环境说明 由于资源有限,gtm一台、另外两台身兼数职。 主机名 IP 角色 端口 nodename 数据目录 gtm 192.168.20.132 GTM 6666 gtm /nodes/gtm 协调器 5432 coord1 /nodes/coordinator xl1 192.168.20.133 数据节点 5433 node1 /nodes/pgdata gtm代理 6666 gtmpoxy01 /nodes/gtm_pxy1 协调器 5432 coord2 /nodes/coordinator xl2 192.168.20.134 数据节点 5433 node2 /nodes/pgdata gtm代理 6666 gtmpoxy02 /nodes/gtm_pxy2 要求 GNU make版本 3.8及以上版本 [root@pg ~] make --versionGNU Make 3.82Built for x86_64-redhat-linux-gnuCopyright (C) 2010 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law. 需安装GCC包 需安装tar包 用于解压缩文件 默认需要GNU Readline library 其作用是可以让psql命令行记住执行过的命令,并且可以通过键盘上下键切换命令。但是可以通过--without-readline禁用这个特性,或者可以指定--withlibedit-preferred选项来使用libedit 默认使用zlib压缩库 可通过--without-zlib选项来禁用 配置hosts 所有主机上都配置 [root@xl2 11] cat /etc/hosts127.0.0.1 localhost192.168.20.132 gtm192.168.20.133 xl1192.168.20.134 xl2 关闭防火墙、Selinux 所有主机都执行 关闭防火墙: [root@gtm ~] systemctl stop firewalld.service[root@gtm ~] systemctl disable firewalld.service selinux设置: [root@gtm ~]vim /etc/selinux/config 设置SELINUX=disabled,保存退出。 This file controls the state of SELinux on the system. SELINUX= can take one of these three values: enforcing - SELinux security policy is enforced. permissive - SELinux prints warnings instead of enforcing. disabled - No SELinux policy is loaded.SELINUX=disabled SELINUXTYPE= can take one of three two values: targeted - Targeted processes are protected, minimum - Modification of targeted policy. Only selected processes are protected. mls - Multi Level Security protection. 安装依赖包 所有主机上都执行 yum install -y flex bison readline-devel zlib-devel openjade docbook-style-dsssl gcc 创建用户 所有主机上都执行 [root@gtm ~] useradd postgres[root@gtm ~] passwd postgres[root@gtm ~] su - postgres[root@gtm ~] mkdir ~/.ssh[root@gtm ~] chmod 700 ~/.ssh 配置SSH免密登录 仅仅在gtm节点配置如下操作: [root@gtm ~] su - postgres[postgres@gtm ~] ssh-keygen -t rsa[postgres@gtm ~] cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys[postgres@gtm ~] chmod 600 ~/.ssh/authorized_keys 将刚生成的认证文件拷贝到xl1到xl2中,使得gtm节点可以免密码登录xl1~xl2的任意一个节点: [postgres@gtm ~] scp ~/.ssh/authorized_keys postgres@xl1:~/.ssh/[postgres@gtm ~] scp ~/.ssh/authorized_keys postgres@xl2:~/.ssh/ 对所有提示都不要输入,直接enter下一步。直到最后,因为第一次要求输入目标机器的用户密码,输入即可。 下载源码 下载地址:https://www.postgres-xl.org/download/ [root@slave ~] ll postgres-xl-10r1.1.tar.gz-rw-r--r-- 1 root root 28121666 May 30 05:21 postgres-xl-10r1.1.tar.gz 编译、安装Postgres-XL 所有节点都安装,编译需要一点时间,最好同时进行编译。 [root@slave ~] tar xvf postgres-xl-10r1.1.tar.gz[root@slave ~] ./configure --prefix=/home/postgres/pgxl/[root@slave ~] make[root@slave ~] make install[root@slave ~] cd contrib/ --安装必要的工具,在gtm节点上安装即可[root@slave ~] make[root@slave ~] make install 配置环境变量 所有节点都要配置 进入postgres用户,修改其环境变量,开始编辑 [root@gtm ~]su - postgres[postgres@gtm ~]vi .bashrc --不是.bash_profile 在打开的文件末尾,新增如下变量配置: export PGHOME=/home/postgres/pgxlexport LD_LIBRARY_PATH=$PGHOME/lib:$LD_LIBRARY_PATHexport PATH=$PGHOME/bin:$PATH 按住esc,然后输入:wq!保存退出。输入以下命令对更改重启生效。 [postgres@gtm ~] source .bashrc --不是.bash_profile 输入以下语句,如果输出变量结果,代表生效 [postgres@gtm ~] echo $PGHOME 应该输出/home/postgres/pgxl代表生效 配置集群 生成pgxc_ctl.conf配置文件 [postgres@gtm ~] pgxc_ctl prepare/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxl/pgxc_ctl/pgxc_ctl_bash.ERROR: File "/home/postgres/pgxl/pgxc_ctl/pgxc_ctl.conf" not found or not a regular file. No such file or directoryInstalling pgxc_ctl_bash script as /home/postgres/pgxl/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxl/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxl/pgxc_ctl --configuration /home/postgres/pgxl/pgxc_ctl/pgxc_ctl.confFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxl/pgxc_ctl 配置pgxc_ctl.conf 新建/home/postgres/pgxc_ctl/pgxc_ctl.conf文件,编辑如下: 对着模板文件一个一个修改,否则会造成初始化过程出现各种神奇问题。 pgxcInstallDir=$PGHOMEpgxlDATA=$PGHOME/data pgxcOwner=postgres---- GTM Master -----------------------------------------gtmName=gtmgtmMasterServer=gtmgtmMasterPort=6666gtmMasterDir=$pgxlDATA/nodes/gtmgtmSlave=y Specify y if you configure GTM Slave. Otherwise, GTM slave will not be configured and all the following variables will be reset.gtmSlaveName=gtmSlavegtmSlaveServer=gtm value none means GTM slave is not available. Give none if you don't configure GTM Slave.gtmSlavePort=20001 Not used if you don't configure GTM slave.gtmSlaveDir=$pgxlDATA/nodes/gtmSlave Not used if you don't configure GTM slave.---- GTM-Proxy Master -------gtmProxyDir=$pgxlDATA/nodes/gtm_proxygtmProxy=y gtmProxyNames=(gtm_pxy1 gtm_pxy2) gtmProxyServers=(xl1 xl2) gtmProxyPorts=(6666 6666) gtmProxyDirs=($gtmProxyDir $gtmProxyDir) ---- Coordinators ---------coordMasterDir=$pgxlDATA/nodes/coordcoordNames=(coord1 coord2) coordPorts=(5432 5432) poolerPorts=(6667 6667) coordPgHbaEntries=(0.0.0.0/0)coordMasterServers=(xl1 xl2) coordMasterDirs=($coordMasterDir $coordMasterDir)coordMaxWALsernder=0 没设置备份节点,设置为0coordMaxWALSenders=($coordMaxWALsernder $coordMaxWALsernder) 数量保持和coordMasterServers一致coordSlave=n---- Datanodes ----------datanodeMasterDir=$pgxlDATA/nodes/dn_masterprimaryDatanode=xl1 主数据节点datanodeNames=(node1 node2)datanodePorts=(5433 5433) datanodePoolerPorts=(6668 6668) datanodePgHbaEntries=(0.0.0.0/0)datanodeMasterServers=(xl1 xl2)datanodeMasterDirs=($datanodeMasterDir $datanodeMasterDir)datanodeMaxWalSender=4datanodeMaxWALSenders=($datanodeMaxWalSender $datanodeMaxWalSender) 集群初始化,启动,停止 初始化 pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf init all 输出结果: /bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlStopping all the coordinator masters.Stopping coordinator master coord1.Stopping coordinator master coord2.pg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord1" does not existpg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord2" does not existDone.Stopping all the datanode masters.Stopping datanode master datanode1.Stopping datanode master datanode2.pg_ctl: PID file "/home/postgres/pgxc/nodes/datanode/datanode1/postmaster.pid" does not existIs server running?Done.Stop GTM masterwaiting for server to shut down.... doneserver stopped[postgres@gtm ~]$ echo $PGHOME/home/postgres/pgxl[postgres@gtm ~]$ ll /home/postgres/pgxl/pgxc/nodes/gtm/gtm.^C[postgres@gtm ~]$ pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf init all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlInitialize GTM masterERROR: target directory (/home/postgres/pgxc/nodes/gtm) exists and not empty. Skip GTM initilializationDone.Start GTM masterserver startingInitialize all the coordinator masters.Initialize coordinator master coord1.ERROR: target coordinator master coord1 is running now. Skip initilialization.Initialize coordinator master coord2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/coord/coord2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting coordinator master.Starting coordinator master coord1ERROR: target coordinator master coord1 is already running now. Skip initialization.Starting coordinator master coord22019-05-30 21:09:25.562 EDT [2148] LOG: listening on IPv4 address "0.0.0.0", port 54322019-05-30 21:09:25.562 EDT [2148] LOG: listening on IPv6 address "::", port 54322019-05-30 21:09:25.563 EDT [2148] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"2019-05-30 21:09:25.601 EDT [2149] LOG: database system was shut down at 2019-05-30 21:09:22 EDT2019-05-30 21:09:25.605 EDT [2148] LOG: database system is ready to accept connections2019-05-30 21:09:25.612 EDT [2156] LOG: cluster monitor startedDone.Initialize all the datanode masters.Initialize the datanode master datanode1.Initialize the datanode master datanode2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode1 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting all the datanode masters.Starting datanode master datanode1.WARNING: datanode master datanode1 is running now. Skipping.Starting datanode master datanode2.2019-05-30 21:09:33.352 EDT [2404] LOG: listening on IPv4 address "0.0.0.0", port 154322019-05-30 21:09:33.352 EDT [2404] LOG: listening on IPv6 address "::", port 154322019-05-30 21:09:33.355 EDT [2404] LOG: listening on Unix socket "/tmp/.s.PGSQL.15432"2019-05-30 21:09:33.392 EDT [2404] LOG: redirecting log output to logging collector process2019-05-30 21:09:33.392 EDT [2404] HINT: Future log output will appear in directory "pg_log".Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done.[postgres@gtm ~]$ pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf stop all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlStopping all the coordinator masters.Stopping coordinator master coord1.Stopping coordinator master coord2.pg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord1" does not existDone.Stopping all the datanode masters.Stopping datanode master datanode1.Stopping datanode master datanode2.pg_ctl: PID file "/home/postgres/pgxc/nodes/datanode/datanode1/postmaster.pid" does not existIs server running?Done.Stop GTM masterwaiting for server to shut down.... doneserver stopped[postgres@gtm ~]$ pgxc_ctl/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlPGXC monitor allNot running: gtm masterRunning: coordinator master coord1Not running: coordinator master coord2Running: datanode master datanode1Not running: datanode master datanode2PGXC stop coordinator master coord1Stopping coordinator master coord1.pg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord1" does not existDone.PGXC stop datanode master datanode1Stopping datanode master datanode1.pg_ctl: PID file "/home/postgres/pgxc/nodes/datanode/datanode1/postmaster.pid" does not existIs server running?Done.PGXC monitor allNot running: gtm masterRunning: coordinator master coord1Not running: coordinator master coord2Running: datanode master datanode1Not running: datanode master datanode2PGXC monitor allNot running: gtm masterNot running: coordinator master coord1Not running: coordinator master coord2Not running: datanode master datanode1Not running: datanode master datanode2PGXC exit[postgres@gtm ~]$ pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf init all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlInitialize GTM masterERROR: target directory (/home/postgres/pgxc/nodes/gtm) exists and not empty. Skip GTM initilializationDone.Start GTM masterserver startingInitialize all the coordinator masters.Initialize coordinator master coord1.Initialize coordinator master coord2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/coord/coord1 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/coord/coord2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting coordinator master.Starting coordinator master coord1Starting coordinator master coord22019-05-30 21:13:03.998 EDT [25137] LOG: listening on IPv4 address "0.0.0.0", port 54322019-05-30 21:13:03.998 EDT [25137] LOG: listening on IPv6 address "::", port 54322019-05-30 21:13:04.000 EDT [25137] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"2019-05-30 21:13:04.038 EDT [25138] LOG: database system was shut down at 2019-05-30 21:13:00 EDT2019-05-30 21:13:04.042 EDT [25137] LOG: database system is ready to accept connections2019-05-30 21:13:04.049 EDT [25145] LOG: cluster monitor started2019-05-30 21:13:04.020 EDT [2730] LOG: listening on IPv4 address "0.0.0.0", port 54322019-05-30 21:13:04.020 EDT [2730] LOG: listening on IPv6 address "::", port 54322019-05-30 21:13:04.021 EDT [2730] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"2019-05-30 21:13:04.057 EDT [2731] LOG: database system was shut down at 2019-05-30 21:13:00 EDT2019-05-30 21:13:04.061 EDT [2730] LOG: database system is ready to accept connections2019-05-30 21:13:04.062 EDT [2738] LOG: cluster monitor startedDone.Initialize all the datanode masters.Initialize the datanode master datanode1.Initialize the datanode master datanode2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode1 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting all the datanode masters.Starting datanode master datanode1.Starting datanode master datanode2.2019-05-30 21:13:12.077 EDT [25392] LOG: listening on IPv4 address "0.0.0.0", port 154322019-05-30 21:13:12.077 EDT [25392] LOG: listening on IPv6 address "::", port 154322019-05-30 21:13:12.079 EDT [25392] LOG: listening on Unix socket "/tmp/.s.PGSQL.15432"2019-05-30 21:13:12.114 EDT [25392] LOG: redirecting log output to logging collector process2019-05-30 21:13:12.114 EDT [25392] HINT: Future log output will appear in directory "pg_log".2019-05-30 21:13:12.079 EDT [2985] LOG: listening on IPv4 address "0.0.0.0", port 154322019-05-30 21:13:12.079 EDT [2985] LOG: listening on IPv6 address "::", port 154322019-05-30 21:13:12.081 EDT [2985] LOG: listening on Unix socket "/tmp/.s.PGSQL.15432"2019-05-30 21:13:12.117 EDT [2985] LOG: redirecting log output to logging collector process2019-05-30 21:13:12.117 EDT [2985] HINT: Future log output will appear in directory "pg_log".Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done. 启动 pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf start all 关闭 pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf stop all 查看集群状态 [postgres@gtm ~]$ pgxc_ctl monitor all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlRunning: gtm masterRunning: coordinator master coord1Running: coordinator master coord2Running: datanode master datanode1Running: datanode master datanode2 配置集群信息 分别在数据节点、协调器节点上分别执行以下命令: 注:本节点只执行修改操作即可(alert node),其他节点执行创建命令(create node)。因为本节点已经包含本节点的信息。 create node coord1 with (type=coordinator,host=xl1, port=5432);create node coord2 with (type=coordinator,host=xl2, port=5432);alter node coord1 with (type=coordinator,host=xl1, port=5432);alter node coord2 with (type=coordinator,host=xl2, port=5432);create node datanode1 with (type=datanode, host=xl1,port=15432,primary=true,PREFERRED);create node datanode2 with (type=datanode, host=xl2,port=15432);alter node datanode1 with (type=datanode, host=xl1,port=15432,primary=true,PREFERRED);alter node datanode2 with (type=datanode, host=xl2,port=15432);select pgxc_pool_reload(); 分别登陆数据节点、协调器节点验证 postgres= select from pgxc_node;node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id-----------+-----------+-----------+-----------+----------------+------------------+-------------coord1 | C | 5432 | xl1 | f | f | 1885696643coord2 | C | 5432 | xl2 | f | f | -1197102633datanode2 | D | 15432 | xl2 | f | f | -905831925datanode1 | D | 15432 | xl1 | t | f | 888802358(4 rows) 测试 插入数据 在数据节点1,执行相关操作。 通过协调器端口登录PG [postgres@xl1 ~]$ psql -p 5432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= create database lei;CREATE DATABASEpostgres= \c lei;You are now connected to database "lei" as user "postgres".lei= create table test1(id int,name text);CREATE TABLElei= insert into test1(id,name) select generate_series(1,8),'测试';INSERT 0 8lei= select from test1;id | name----+------1 | 测试2 | 测试5 | 测试6 | 测试8 | 测试3 | 测试4 | 测试7 | 测试(8 rows) 注:默认创建的表为分布式表,也就是每个数据节点值存储表的部分数据。关于表类型具体说明,下面有说明。 通过15432端口登录数据节点,查看数据 有5条数据 [postgres@xl1 ~]$ psql -p 15432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= \c lei;You are now connected to database "lei" as user "postgres".lei= select from test1;id | name----+------1 | 测试2 | 测试5 | 测试6 | 测试8 | 测试(5 rows) 登录到节点2,查看数据 有3条数据 [postgres@xl2 ~]$ psql -p15432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= \c lei;You are now connected to database "lei" as user "postgres".lei= select from test1;id | name----+------3 | 测试4 | 测试7 | 测试(3 rows) 两个节点的数据加起来整个8条,没有问题。 至此Postgre-XL集群搭建完成。 创建数据库、表时可能会出现以下错误: ERROR: Failed to get pooled connections 是因为pg_hba.conf配置不对,所有节点加上host all all 192.168.20.0/0 trust并重启集群即可。 ERROR: No Datanode defined in cluster 首先确认是否创建了数据节点,也就是create node相关的命令。如果创建了则执行select pgxc_pool_reload();使其生效即可。 集群管理与应用 表类型说明 REPLICATION表:各个datanode节点中,表的数据完全相同,也就是说,插入数据时,会分别在每个datanode节点插入相同数据。读数据时,只需要读任意一个datanode节点上的数据。 建表语法: CREATE TABLE repltab (col1 int, col2 int) DISTRIBUTE BY REPLICATION; DISTRIBUTE :会将插入的数据,按照拆分规则,分配到不同的datanode节点中存储,也就是sharding技术。每个datanode节点只保存了部分数据,通过coordinate节点可以查询完整的数据视图。 CREATE TABLE disttab(col1 int, col2 int, col3 text) DISTRIBUTE BY HASH(col1); 模拟数据插入 任意登录一个coordinate节点进行建表操作 [postgres@gtm ~]$ psql -h xl1 -p 5432 -U postgrespostgres= INSERT INTO disttab SELECT generate_series(1,100), generate_series(101, 200), 'foo';INSERT 0 100postgres= INSERT INTO repltab SELECT generate_series(1,100), generate_series(101, 200);INSERT 0 100 查看数据分布结果: DISTRIBUTE表分布结果 postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;xc_node_id | count ------------+-------1148549230 | 42-927910690 | 58(2 rows) REPLICATION表分布结果 postgres= SELECT count() FROM repltab;count -------100(1 row) 查看另一个datanode2中repltab表结果 [postgres@datanode2 pgxl9.5]$ psql -p 15432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= SELECT count() FROM repltab;count -------100(1 row) 结论:REPLICATION表中,datanode1,datanode2中表是全部数据,一模一样。而DISTRIBUTE表,数据散落近乎平均分配到了datanode1,datanode2节点中。 新增数据节点与数据重分布 在线新增节点、并重新分布数据。 新增datanode节点 在gtm集群管理节点上执行pgxc_ctl命令 [postgres@gtm ~]$ pgxc_ctl/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.confFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlPGXC 在服务器xl3上,新增一个master角色的datanode节点,名称是datanode3 端口号暂定5430,pool master暂定6669 ,指定好数据目录位置,从两个节点升级到3个节点,之后要写3个none none应该是datanodeSpecificExtraConfig或者datanodeSpecificExtraPgHba配置PGXC add datanode master datanode3 xl3 15432 6671 /home/postgres/pgxc/nodes/datanode/datanode3 none none none 等待新增完成后,查询集群节点状态: postgres= select from pgxc_node;node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id-----------+-----------+-----------+-----------+----------------+------------------+-------------datanode1 | D | 15432 | xl1 | t | f | 888802358datanode2 | D | 15432 | xl2 | f | f | -905831925datanode3 | D | 15432 | xl3 | f | f | -705831925coord1 | C | 5432 | xl1 | f | f | 1885696643coord2 | C | 5432 | xl2 | f | f | -1197102633(4 rows) 节点新增完毕 数据重新分布 由于新增节点后无法自动完成数据重新分布,需要手动操作。 DISTRIBUTE表分布在了node1,node2节点上,如下: postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;xc_node_id | count ------------+-------1148549230 | 42-927910690 | 58(2 rows) 新增一个节点后,将sharding表数据重新分配到三个节点上,将repl表复制到新节点 重分布sharding表postgres= ALTER TABLE disttab ADD NODE (datanode3);ALTER TABLE 复制数据到新节点postgres= ALTER TABLE repltab ADD NODE (datanode3);ALTER TABLE 查看新的数据分布: postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;xc_node_id | count ------------+--------700122826 | 36-927910690 | 321148549230 | 32(3 rows) 登录datanode3(新增的时候,放在了xl3服务器上,端口15432)节点查看数据: [postgres@gtm ~]$ psql -h xl3 -p 15432 -U postgrespsql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= select count() from repltab;count -------100(1 row) 很明显,通过 ALTER TABLE tt ADD NODE (dn)命令,可以将DISTRIBUTE表数据重新分布到新节点,重分布过程中会中断所有事务。可以将REPLICATION表数据复制到新节点。 从datanode节点中回收数据 postgres= ALTER TABLE disttab DELETE NODE (datanode3);ALTER TABLEpostgres= ALTER TABLE repltab DELETE NODE (datanode3);ALTER TABLE 删除数据节点 Postgresql-XL并没有检查将被删除的datanode节点是否有replicated/distributed表的数据,为了数据安全,在删除之前需要检查下被删除节点上的数据,有数据的话,要回收掉分配到其他节点,然后才能安全删除。删除数据节点分为四步骤: 1.查询要删除节点dn3的oid postgres= SELECT oid, FROM pgxc_node;oid | node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id -------+-----------+-----------+-----------+-----------+----------------+------------------+-------------11819 | coord1 | C | 5432 | datanode1 | f | f | 188569664316384 | coord2 | C | 5432 | datanode2 | f | f | -119710263316385 | node1 | D | 5433 | datanode1 | f | t | 114854923016386 | node2 | D | 5433 | datanode2 | f | f | -92791069016397 | dn3 | D | 5430 | datanode1 | f | f | -700122826(5 rows) 2.查询dn3对应的oid中是否有数据 testdb= SELECT FROM pgxc_class WHERE nodeoids::integer[] @> ARRAY[16397];pcrelid | pclocatortype | pcattnum | pchashalgorithm | pchashbuckets | nodeoids ---------+---------------+----------+-----------------+---------------+-------------------16388 | H | 1 | 1 | 4096 | 16397 16385 1638616394 | R | 0 | 0 | 0 | 16397 16385 16386(2 rows) 3.有数据的先回收数据 postgres= ALTER TABLE disttab DELETE NODE (dn3);ALTER TABLEpostgres= ALTER TABLE repltab DELETE NODE (dn3);ALTER TABLEpostgres= SELECT FROM pgxc_class WHERE nodeoids::integer[] @> ARRAY[16397];pcrelid | pclocatortype | pcattnum | pchashalgorithm | pchashbuckets | nodeoids ---------+---------------+----------+-----------------+---------------+----------(0 rows) 4.安全删除dn3 PGXC$ remove datanode master dn3 clean 故障节点FAILOVER 1.查看当前集群状态 [postgres@gtm ~]$ psql -h xl1 -p 5432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= SELECT oid, FROM pgxc_node;oid | node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id-------+-----------+-----------+-----------+-----------+----------------+------------------+-------------11739 | coord1 | C | 5432 | xl1 | f | f | 188569664316384 | coord2 | C | 5432 | xl2 | f | f | -119710263316387 | datanode2 | D | 15432 | xl2 | f | f | -90583192516388 | datanode1 | D | 15432 | xl1 | t | t | 888802358(4 rows) 2.模拟datanode1节点故障 直接关闭即可 PGXC stop -m immediate datanode master datanode1Stopping datanode master datanode1.Done. 3.测试查询 只要查询涉及到datanode1上的数据,那么该查询就会报错 postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;WARNING: failed to receive file descriptors for connectionsERROR: Failed to get pooled connectionsHINT: This may happen because one or more nodes are currently unreachable, either because of node or network failure.Its also possible that the target node may have hit the connection limit or the pooler is configured with low connections.Please check if all nodes are running fine and also review max_connections and max_pool_size configuration parameterspostgres= SELECT xc_node_id, FROM disttab WHERE col1 = 3;xc_node_id | col1 | col2 | col3------------+------+------+-------905831925 | 3 | 103 | foo(1 row) 测试发现,查询范围如果涉及到故障的node1节点,会报错,而查询的数据范围不在node1上的话,仍然可以查询。 4.手动切换 要想切换,必须要提前配置slave节点。 PGXC$ failover datanode node1 切换完成后,查询集群 postgres= SELECT oid, FROM pgxc_node;oid | node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id -------+-----------+-----------+-----------+-----------+----------------+------------------+-------------11819 | coord1 | C | 5432 | datanode1 | f | f | 188569664316384 | coord2 | C | 5432 | datanode2 | f | f | -119710263316386 | node2 | D | 15432 | datanode2 | f | f | -92791069016385 | node1 | D | 15433 | datanode2 | f | t | 1148549230(4 rows) 发现datanode1节点的ip和端口都已经替换为配置的slave了。 本篇文章为转载内容。原文链接:https://blog.csdn.net/qianglei6077/article/details/94379331。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-30 11:09:03
94
转载
Datax
... Datax作为一款高效的离线ETL工具,被广泛应用于企业级大数据处理中。不过话说回来,现如今数据量蹭蹭地涨,大家伙儿对数据准不准、靠不靠谱这个问题可是越来越上心了。嘿,大家伙儿!接下来我要跟你们分享一下,在使用Datax这款工具时,如何从几个关键点出发,确保咱们处理的数据既准确又可靠,一步到位,稳稳当当的。 二、Datax的数据质量检查 在Datax的流程设置中,我们可以加入数据质量检查环节。比如,我们可以动手给数据安个过滤器,把那些重复的数据小弟踢出去,或者来个华丽变身,把不同类型的数据转换成我们需要的样子,这样一来,咱们手头的数据质量就能蹭蹭往上涨啦! 以下是一个简单的数据去重的例子: java public void execute(EnvContext envContext) { String sql = "SELECT FROM table WHERE id > 0"; TableInserter inserter = getTableInserter(envContext); try { inserter.init(); QueryResult queryResult = SqlRunner.run(sql, DatabaseType.H2); for (Row row : queryResult.getRows()) { inserter.insert(row); } } catch (Exception e) { throw new RuntimeException(e); } finally { inserter.close(); } } 在这个例子中,我们首先通过SQL查询获取到表中的所有非空行,然后将这些行插入到目标表中。这样,我们就避免了数据的重复插入。 三、Datax的数据验证 在数据传输过程中,我们还需要进行数据验证,以确保数据的正确性。例如,我们可以通过校验数据是否满足某种规则,来判断数据的有效性。 以下是一个简单的数据校验的例子: java public boolean isValid(String data) { return Pattern.matches("\\d{3}-\\d{8}", data); } 在这个例子中,我们定义了一个正则表达式,用于匹配手机号码。如果输入的数据恰好符合我们设定的这个正则表达式的规矩,那咱就可以拍着胸脯说,这个数据是完全OK的,是有效的。 四、Datax的数据清洗 在数据传输的过程中,我们还可能会遇到一些异常情况,如数据丢失、数据损坏等。在这种情况下,我们需要对数据进行清洗,以恢复数据的完整性和一致性。 以下是一个简单的数据清洗的例子: java public void cleanUp(EnvContext envContext) { String sql = "UPDATE table SET column1 = NULL WHERE column2 = 'error'"; SqlRunner.run(sql, DatabaseType.H2); } 在这个例子中,我们通过SQL语句,将表中column2为'error'的所有记录的column1字段设为NULL。这样,我们就清除了这些异常数据的影响。 五、结论 在使用Datax进行数据处理时,我们需要关注数据的质量、正确性和完整性等问题。通过严谨地给数据“体检”、反复验证其真实性,再仔仔细细地给它“洗个澡”,我们就能确保数据的准确度和可靠性蹭蹭上涨,真正做到让数据靠谱起来。同时呢,我们也要持续地改进咱们的数据处理方法,好让它们能灵活适应各种不断变化的数据环境,跟上时代步伐。
2023-05-23 08:20:57
281
柳暗花明又一村-t
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
ssh user@hostname
- 远程登录到另一台Linux主机。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"