前端技术
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
[元组 Tuple ]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
转载文章
...内容。 Java中的元组Tuple 文章目录 Java中的元组Tuple 1. 概念 2. 使用 2.1 依赖Jar包 2.2 基本使用 2.2.1 直接调用 2.2.2 自定义工具类 2.2.3 示例代码 1. 概念 Java中的Tuple是一种数据结构,可存放多个元素,每个元素的数据类型可不同。Tuple与List集合类似,但是不同的是,List集合只能存储一种数据类型,而Tuple可存储多种数据类型。 可能你会说,Object类型的List实际也是可以存储多种类型的啊?但是在创建List的时候,需要指定元素数据类型,也就是只能指定为Object类型,获取的元素类型就是Object,如有需要则要进行强转。而Tuple在创建的时候,则可以直接指定多个元素数据类型。 Tuple具体是怎么的数据结构呢? 元组(tuple)是关系数据库中的基本概念,关系是一张表,表中的每行(即数据库中的每条记录)就是一个元组,每列就是一个属性。 在二维表里,元组也称为行。 以上是百度百科中的"元组"概念,我们将一个元组理解为数据表中的一行,而一行中每个字段的类型是可以不同的。这样我们就可以简单理解Java中的Tuple数据结构了。 2. 使用 2.1 依赖Jar包 Maven坐标如下: <dependency><groupId>org.javatuples</groupId><artifactId>javatuples</artifactId><version>1.2</version></dependency> 引入相关依赖后,可以看出jar包中的结构很简单,其中的类主要是tuple基础类、扩展的一元组、二元组…十元组,以及键值对元组;接口的作用是提供【获取创建各元组时传入参数值】的方法。 2.2 基本使用 2.2.1 直接调用 以下以三元组为例,部分源码如下: package org.javatuples;import java.util.Collection;import java.util.Iterator;import org.javatuples.valueintf.IValue0;import org.javatuples.valueintf.IValue1;import org.javatuples.valueintf.IValue2;/ <p> A tuple of three elements. </p> @since 1.0 @author Daniel Fernández/public final class Triplet<A,B,C> extends Tupleimplements IValue0<A>,IValue1<B>,IValue2<C> {private static final long serialVersionUID = -1877265551599483740L;private static final int SIZE = 3;private final A val0;private final B val1;private final C val2;public static <A,B,C> Triplet<A,B,C> with(final A value0, final B value1, final C value2) {return new Triplet<A,B,C>(value0,value1,value2);} 我们一般调用静态方法with,传入元组数据,创建一个元组。当然了,也可以通过有参构造、数组Array、集合Collection、迭代器Iterator来创建一个元组,直接调用相应方法即可。 但是,我们可能记不住各元组对象的名称(Unit、Pair、Triplet、Quartet、Quintet、Sextet、Septet、Octet、Ennead、Decade),还要背下单词…因此,我们可以自定义一个工具类,提供公共方法,根据传入的参数个数,返回不同的元组对象。 2.2.2 自定义工具类 package com.superchen.demo.utils;import org.javatuples.Decade;import org.javatuples.Ennead;import org.javatuples.Octet;import org.javatuples.Pair;import org.javatuples.Quartet;import org.javatuples.Quintet;import org.javatuples.Septet;import org.javatuples.Sextet;import org.javatuples.Triplet;import org.javatuples.Unit;/ ClassName: TupleUtils Function: <p> Tuple helper to create numerous items of tuple. the maximum is 10. if you want to create tuple which elements count more than 10, a new class would be a better choice. if you don't want to new a class, just extends the class {@link org.javatuples.Tuple} and do your own implemention. </p> date: 2019/9/2 16:16 @version 1.0.0 @author Chavaer @since JDK 1.8/public class TupleUtils{/ <p>Create a tuple of one element.</p> @param value0 @param <A> @return a tuple of one element/public static <A> Unit<A> with(final A value0) {return Unit.with(value0);}/ <p>Create a tuple of two elements.</p> @param value0 @param value1 @param <A> @param <B> @return a tuple of two elements/public static <A, B> Pair<A, B> with(final A value0, final B value1) {return Pair.with(value0, value1);}/ <p>Create a tuple of three elements.</p> @param value0 @param value1 @param value2 @param <A> @param <B> @param <C> @return a tuple of three elements/public static <A, B, C> Triplet<A, B, C> with(final A value0, final B value1, final C value2) {return Triplet.with(value0, value1, value2);} } 以上的TupleUtils中提供了with的重载方法,调用时根据传入的参数值个数,返回对应的元组对象。 2.2.3 示例代码 若有需求: 现有pojo类Student、Teacher、Programmer,需要存储pojo类的字节码文件、对应数据库表的主键名称、对应数据库表的毕业院校字段名称,传到后层用于组装sql。 可以再定义一个对象类,但是如果还要再添加条件字段的话,又得重新定义…所以我们这里直接使用元组Tuple实现。 public class TupleTest {public static void main(String[] args) {List<Triplet<Class, String, String>> roleList = new ArrayList<Triplet<Class, String, String>>();/三元组,存储数据:对应实体类字节码文件、数据表主键名称、数据表毕业院校字段名称/Triplet<Class, String, String> studentTriplet = TupleUtils.with(Student.class, "sid", "graduate");Triplet<Class, String, String> teacherTriplet = TupleUtils.with(Teacher.class, "tid", "graduate");Triplet<Class, String, String> programmerTriplet = TupleUtils.with(Programmer.class, "id", "graduate");roleList.add(studentTriplet);roleList.add(teacherTriplet);roleList.add(programmerTriplet);for (Triplet<Class, String, String> triplet : roleList) {System.out.println(triplet);} }} 存储数据结构如下: 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_35006663/article/details/100301416。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-09-17 17:43:51
257
转载
Apache Pig
... (10)映射型:tuple Pig中的映射型是一个包含两个不同类型的键值对的元组。例如: php-template j = (1, 'apple'); (11)映射数组型:map Pig中的映射数组型是一个包含多个键值对的列表。例如: bash k = {'key1': 'value1', 'key2': 'value2'}; 2. 复杂类型 Pig中的复杂数据类型主要有两种:列表和文件。 (1)列表:list Pig中的列表是一个包含多个相同类型元素的列表。例如: php-template l = [1, 2, 3]; (2)文件:file Pig中的文件是一个包含多个行的数据文件。例如: makefile m = '/path/to/file.txt'; 3. 特殊类型 Pig中的特殊数据类型主要有三种:null、undefined和struct。 (1)null:null Pig中的null表示一个空值。例如: java n = null; (2)undefined:undefined Pig中的undefined表示一个未定义的值。例如: python o = undefined;
2023-01-14 19:17:59
480
诗和远方-t
Mahout
....api.java.tuple.Tuple2; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; public class RealtimeRecommendationSystem { public static void main(String[] args) throws Exception { // 创建流处理环境 StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); // 假设我们有一个实时事件流,包含用户ID和商品ID DataStream> eventStream = env.fromElements( Tuple2.of("user1", "itemA"), Tuple2.of("user2", "itemB"), Tuple2.of("user1", "itemC") ); // 使用Mahout的协同过滤算法进行实时推荐 DataStream> recommendations = eventStream.map(new MapFunction, Tuple2>() { @Override public Tuple2 map(Tuple2 value) { // 这里只是一个示例,实际应用中需要调用具体的协同过滤算法 return new Tuple2<>(value.f0, "recommendedItem"); } }); // 打印输出 recommendations.print(); // 执行任务 env.execute("Realtime Recommendation System"); } } 四、结论 开启数据驱动的未来 通过整合Mahout的机器学习能力和Flink的实时计算能力,开发者能够构建出响应迅速、高效精准的数据分析系统。无论是实时推荐、大规模聚类还是在线协同过滤,这些功能都为数据分析带来了新的可能。哎呀,随着科技这玩意儿越变越厉害,咱们能见到的新鲜事儿也是一波接一波。就像是魔法一样,数据这东西,现在能帮咱们推动业务发展,搞出不少新花样,让咱们的生意越来越红火,创意源源不断。简直就像开了挂一样!
2024-09-01 16:22:51
60
海阔天空
转载文章
...ort 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
转载
Python
...)) return tuple(component / magnitude for component in vector) 调用方法执行计算 vector = (3, 4, 5) unit_vector = unit_vector(vector) print(f"The unit vector of {vector} is {unit_vector}") 在上面的代码中,我们先设定了一个unit_vector()方法,用以计算一个矢量的单位矢量。该方法需要一个矢量作为输入参数,通过对矢量每个元素的平方求和,再将结果的平方根作为分母来计算单位矢量的每个元素。最后,我们打印出计算结果。 如需计算其他矢量的单位矢量,只需要更改vector变量的值,并再次调用unit_vector()方法即可。
2023-03-29 15:10:37
50
算法侠
Python
...有数据结构(如列表、元组或范围)快速生成新列表,同时可以结合条件判断实现对元素的选择和转换。例如,在“外星人入侵”游戏中,如果需要移除外星人并创建一个新的不包含已消灭外星人的列表,可以使用列表推导式来避免直接修改原列表带来的索引错误等问题。 反模式(Anti-Pattern) , 在软件工程领域,反模式是指那些常见但有害于程序设计、效率或者可维护性的实践或结构。在文中引用《Effective Python》一书中提到的“在对容器元素进行迭代的同时对其进行修改”,就是一种反模式行为。这意味着在遍历列表或其他可变集合的过程中直接删除或修改元素,可能导致不可预期的结果,比如索引错误。在外星人入侵游戏中,直接在循环中移除被击中的外星人就可能引发这类问题,正确的做法是先记录待删除的外星人,然后在遍历结束后再统一执行删除操作。
2023-12-10 11:15:11
201
昨夜星辰昨夜风_t
Python
...型数据结构(如列表、元组等)时尤为常用。在Python中,可以通过for循环配合in关键字来遍历列表中的每个元素。文中示例代码通过“for num in num_list:”这一语句实现了对列表num_list的循环遍历,使得程序能够依次检查并处理列表中的每一个数值元素。在解决正数求和问题时,循环遍历是筛选并累加正数的核心机制。
2023-04-28 23:59:16
1590
软件工程师
JSON
...象(如字符串、数字、元组等)的无序集合。每个项由一个唯一的键和与之关联的值组成,键和值之间通过冒号分隔,各对键值之间用逗号分隔,并放在花括号内。在处理JSON数据时,JSON对象通常会被转换为Python字典,以便在Python程序内部进行操作和处理。 JSON注入 , 类似于SQL注入,JSON注入是一种安全漏洞,攻击者通过向应用提交恶意构造的JSON数据,利用目标应用程序未能有效验证或清理用户输入的问题,进而影响服务器端JSON解析器的行为,以达到篡改数据、执行非预期操作或获取敏感信息的目的。在Python中使用json.loads()方法解析JSON字符串时,应结合严格的数据验证和清理措施来防止JSON注入攻击。
2024-03-03 16:01:36
529
码农
Python
...,例如字符串、列表、元组等。 总之,Python提供了方便简单的语法来对正值和负值进行相加。而且,Python的相加还可以适用于多种数据类型。这为我们的编程工作提供了更多的灵活性和可操作性。
2023-05-02 19:24:10
336
软件工程师
Flink
...Function, Tuple2, TimeWindow>() { @Override public void process(TimeWindow window, Context context, Iterable> values, Collector> out) throws Exception { int count = 0; for (Tuple2 value : values) { if (value.f1.getUserId() == value.f0.getId()) { count++; } } if (count > 1) { out.collect(new Tuple2<>(value.f0, value.f1)); } } }); 在这个示例中,我们首先创建了两个动态表users和orders。然后,我们捣鼓出了一个叫userToOrderKeyMapper的神奇小函数,它的任务就是把用户对象摇身一变,变成订单键对象。接着,我们使用这个映射函数将users表转换为orderKeys表。 接下来,我们使用JOIN操作将orders表和orderKeys表进行JOIN。在JOIN操作这个环节,我们搞了个挺实用的小玩意儿叫键选择器where,它就像是个挖掘工,专门从那个orders表格里头找出来每个订单的关键信息。我们也定义了一个键选择器equalTo,它从users表中提取出用户对象。
2023-02-08 23:59:51
369
秋水共长天一色-t
Apache Pig
... define T tuple(t1:(i1:int, i2:int)); A = load 'input' as (f1: T); B = foreach A generate t1.i1, t1.i2; store B into 'output'; 在这个例子中,我们首先定义了一个名为“T”的嵌套数据类型,然后加载了一个三维数组,最后生成一个新的数组,其中每一项都是原数组的元素的第一个子元素的第一和第二个子元素的值。 四、总结 总的来说,Apache Pig提供了多种方法来处理多维数据。甭管你是用通配符还是嵌套数据类型,都能妥妥地应对海量的多维度数据难题。如果你现在正琢磨着找个牛叉的大数据处理工具,那我必须得提一嘴Apache Pig,这玩意儿绝对是你的不二之选。
2023-05-21 08:47:11
453
素颜如水-t
Python
...点数、字符串、列表、元组、字典等。每种数据类型都有其特定的行为方式和操作方法。例如,字符串用于表示文本信息,列表则是有序且可变的一组元素集合。 调试器 , 调试器是一种软件开发工具,用于查找和修复代码中的错误(也称为“调试”)。在Python中,pdb是内建的调试器,它可以逐行运行代码,设置断点,在运行时查看变量值,以及跟踪程序流程。通过使用调试器,开发者能够深入理解代码执行过程,快速定位问题所在。 错误处理 , 在Python编程中,错误处理是指预见并妥善应对可能出现的程序错误的过程。Python通过异常机制实现错误处理,当程序发生错误时会抛出一个异常对象,程序员可以通过try-except语句捕获异常并对之进行适当的处理,从而避免程序因未捕获异常而崩溃。例如,当尝试打开一个不存在的文件时,Python会抛出FileNotFoundError异常,通过except FileNotFoundError: 语句可以捕获这个异常,并采取合适的恢复措施。
2023-06-06 20:35:24
123
键盘勇士
Flink
...de public Tuple2 map(String value) throws Exception { return new Tuple2<>(value.split(",")[0], Integer.parseInt(value.split(",")[1])); } }) .keyBy(0) .sum(1) .addSink(new PrintSinkFunction<>()); env.enableCheckpointing(5000); env.setStateBackend(new FsStateBackend("hdfs://path/to/state/backend")); 在这个例子中,我们使用了Kafka作为数据源,然后对输入的数据进行简单的映射和聚合操作。通过开启Checkpoint并设置好状态后端,我们确保应用即使重启,也能迅速恢复状态,继续处理新数据。这样就不用担心重启时要从头再来啦! 4. 总结与反思 通过上述讨论,我们可以看到,Flink提供的Checkpoint和Savepoint机制极大地提升了数据冷启动的可重用性。选择合适的状态后端也是关键因素之一。当然啦,这些办法也不是一用就万事大吉的,还得根据实际情况不断调整和优化呢。 希望这篇文章能帮助你更好地理解和解决FlinkJob数据冷启动的可重用性问题。如果你有任何疑问或者有更好的解决方案,欢迎在评论区留言交流!
2024-12-27 16:00:23
37
彩虹之上
Scala
...,通常会得到一系列的元组。如果我们想进一步操作这些元组,就需要先将其转换为对象。这时,隐式转换就派上用场了。 scala val people = Seq(("Alice", 25), ("Bob", 30), ("Charlie", 35)) people.map { case (name, age) => Person(name, age) } 在这个例子中,我们首先定义了一个包含三个元组的序列。然后,我们使用map函数将这些元组转换为Person对象。因为Person这个对象在创建的时候,它的构造函数需要我们提供两个参数,所以呢,我们就得用上case语句这把“解包神器”,来把元组里的信息给巧妙地提取出来。这个过程中,我们就用到了隐式转换。 六、总结 通过本文,我们了解了什么是隐式转换,以及为什么要使用隐式转换。我们也实实在在地学了几个接地气的例子,这下子可是真真切切地感受到了隐式转换在编程世界里的大显身手和关键作用。在未来的学习和工作中,咱们真该好好地跟“隐式转换”这位大拿交朋友,把它摸得门儿清,用得溜溜的。 总的来说,使用隐式转换可以极大地提高API的易用性,使我们的编程工作更加轻松愉快。作为一名码农,咱可不能停下脚步,得时刻保持对新鲜技术和工具的好奇心,不断磨练自己的编程技艺,让技术水平蹭蹭往上涨。因为编程不仅仅是一门技术,更是一种艺术。
2023-12-20 23:23:54
69
凌波微步-t
转载文章
...内容。 标题:递增三元组 给定三个整数数组 A = [A1, A2, ... AN], B = [B1, B2, ... BN], C = [C1, C2, ... CN], 请你统计有多少个三元组(i, j, k) 满足: 1. 1 <= i, j, k <= N 2. Ai < Bj < Ck 【输入格式】 第一行包含一个整数N。 第二行包含N个整数A1, A2, ... AN。 第三行包含N个整数B1, B2, ... BN。 第四行包含N个整数C1, C2, ... CN。 对于30%的数据,1 <= N <= 100 对于60%的数据,1 <= N <= 1000 对于100%的数据,1 <= N <= 100000 0 <= Ai, Bi, Ci <= 100000 【输出格式】 一个整数表示答案 【样例输入】 3 1 1 1 2 2 2 3 3 3 【样例输出】 27 资源约定: 峰值内存消耗(含虚拟机) < 256M CPU消耗 < 1000ms 请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。 注意: main函数需要返回0; 只使用ANSI C/ANSI C++ 标准; 不要调用依赖于编译环境或操作系统的特殊函数。 所有依赖的函数必须明确地在源文件中 include <xxx> 不能通过工程设置而省略常用头文件。 提交程序时,注意选择所期望的语言类型和编译器类型。 题意描述: 就是 a[i] < b[j] < c[k]的有多少组,刚开始想的很简单就是三重训话,当然不对了 解题思路: 找出比b小的所有数a并把个数存到数组x中,然后再找到比b大的所有个数c同时与x相乘即可。 程序代码: include<stdio.h>include<algorithm>using namespace std;int a[100010],b[100010],c[100010];int x[100010];int main(){int i,j,n,count=0;scanf("%d",&n);for(i=0;i<n;i++)scanf("%d",&a[i]);for(i=0;i<n;i++)scanf("%d",&b[i]);for(i=0;i<n;i++)scanf("%d",&c[i]);sort(a,a+n);sort(b,b+n);sort(c,c+n);i=n-1;j=n-1;while(i>=0&&j>=0){if(a[i]<b[j]){x[j]=i+1;j--;}elsei--;}i=0;j=0;while(i<n&&j<n){if(b[i]<c[j]){count+=x[i](n-j);i++;} elsej++;} printf("%d\n",count);return 0;} 本篇文章为转载内容。原文链接:https://hezhiying.blog.csdn.net/article/details/88077408。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-25 23:06:26
333
转载
Apache Pig
...mp)三个字段的数据元组。 (2)数据清洗与转换 接着,我们可能需要对数据进行清洗或转换。比如,我们要提取出所有用户的活跃天数,可以这样做: pig -- 定义一天的时间跨度为86400秒 daily_activity = FOREACH logs GENERATE user, DATEDIFF(TODAY(), FROM_UNIXTIME(timestamp)) as active_days; (3)分组与聚合 进一步,我们可以按照用户进行分组并计算每个用户的总活跃天数: pig user_activity = GROUP daily_activity BY user; total_activity = FOREACH user_activity GENERATE group, SUM(daily_activity.active_days); (4)排序与输出 最后,我们可以按总活跃天数降序排序并存储结果: pig sorted_activity = ORDER total_activity BY $1 DESC; STORE sorted_activity INTO 'output_path'; 3. Pig在复杂数据分析中的优势 在面对复杂数据集时,Pig的优势尤为明显。它的链式操作模式使得我们可以轻松构建复杂的数据处理流水线。同时,Pig还具有优化器,能够自动优化我们的脚本,确保在Hadoop集群上高效执行。另外,Pig提供的UDF(用户自定义函数)这个超级棒的功能,让我们能够随心所欲地定制函数,专门解决那些特定的业务问题,这样一来,数据分析工作就变得更加灵活、更接地气了。 4. 思考与探讨 在实际应用中,Apache Pig不仅让我们从繁杂的MapReduce编程中解脱出来,更能聚焦于数据本身以及所要解决的问题。每次我捣鼓Pig Latin脚本,感觉就像是在和数据面对面唠嗑,一起挖掘埋藏在海量信息海洋中的宝藏秘密。这种“对话”的过程,既是数据分析师的日常挑战,也是Apache Pig赋予我们的乐趣所在。它就像给我们在浩瀚大数据海洋中找方向的灯塔一样,把那些复杂的分析任务变得轻松易懂,简明扼要,让咱一眼就能看明白。 总结来说,Apache Pig凭借其直观的语言结构和高效的数据处理能力,成为了大数据时代复杂数据分析的重要利器。甭管你是刚涉足大数据这片江湖的小白,还是身经百战的数据老炮儿,只要肯下功夫学好Apache Pig这套“武林秘籍”,保管你的数据处理功力和效率都能蹭蹭往上涨,这样一来,就能更好地为业务的腾飞和决策的制定保驾护航啦!
2023-04-05 17:49:39
643
翡翠梦境
Flink
...Function, Tuple2>() { @Override public Tuple2 map(Tuple2 value) throws Exception { // 将字符串转为整数 return new Tuple2<>(value.f0, Integer.parseInt(value.f1)); } }); Pattern, Tuple2> pattern = Pattern., Tuple2>begin("start") .where(new FilterFunction>() { @Override public boolean filter(Tuple2 value) throws Exception { // 判断是否满足条件 return value.f1 > 10; } }) .next("middle") .where(new FilterFunction>() { @Override public boolean filter(Tuple2 value) throws Exception { // 判断是否满足条件 return value.f1 > 20; } }) .followedByAny("end"); DataStream>> results = pattern.grep(stream); results.print(); env.execute("Flink CEP Example"); 这段代码中,我们首先定义了一个事件模式,该模式包含三个事件,分别名为“start”、“middle”和“end”。然后,我们就在这串输入数据流里头“抓”这个模式,一旦逮到匹配的,就把它全都给打印出来。拿这个例子来说吧,我们想象一下,“start”就像是你按下开关启动一台机器的那一刻;“middle”呢,就好比这台机器正在呼呼运转,忙得不可开交的时候;而“end”呢,就是指你再次关掉开关,让设备安静地停止工作的那个时刻。设备一旦启动运转起来,要是过了10秒这家伙还在持续运行没停下来的话,那咱们就可以把它判定为“不正常行为”啦。 2. 实时推荐系统 在实时推荐系统中,我们需要根据用户的实时行为数据生成个性化的推荐结果。Flink CEP可以帮助我们实现实时的推荐计算。 python from pyflink.datastream import StreamExecutionEnvironment, DataStream, ValueStateDescriptor from pyflink.table import DataTypes, TableConfig, StreamTableEnvironment, Schema, \ BatchTableEnvironment, TableSchema, Field, StreamTableApi env = StreamExecutionEnvironment.get_execution_environment() t_config = TableConfig() t_env = StreamTableEnvironment.create(env, t_config) source = ... t_env.connect JDBC("url", "username", "password") \ .with_schema(Schema.new_builder() \ .field("user_id", DataTypes.STRING()) \ .field("product_id", DataTypes.STRING()) \ .field("timestamp", DataTypes.TIMESTAMP(3)) \ .build()) \ .with_name("stream_table") \ .create_temporary_view() pattern = Pattern( from_elements("order", DataTypes.STRING()), OneOrMore( PatternUnion( Pattern.of_type(DataTypes.STRING()).equalTo("purchase"), Pattern.of_type(DataTypes.STRING()).equalTo("click"))), to_elements("session")) result = pattern.apply(t_env.scan("stream_table")) result.select("order_user_id").print_to_file("/tmp/output") env.execute("CEP example") 在这段代码中,我们首先创建了一个表环境,并从JDBC连接读取了一张表。然后,我们定义了一个事件模式,该模式包含了两个事件:“order”和“session”。最后,我们使用这个模式来筛选表中的数据,并将结果保存到文件中。这个例子呢,我们把“order”想象成一次买买买的行动,而“session”呢,就相当于一个会话的开启或者结束,就像你走进商店开始挑选商品到结账离开的整个过程。当用户连续两次剁手买东西,或者接连点啊点的,我们就会觉得这位朋友可真是活跃得不得了,然后我们就把他的用户ID美滋滋地记到文件里去。 3. 实时告警系统 在实时告警系统中,我们需要在接收到实时数据后立即发送告警。Flink CEP可以帮助我们实现实时的告
2023-06-17 10:48:34
452
凌波微步-t
转载文章
...方法,它返回的是一个元组,含有两个对象的重索引版本: 另一个不可或缺的功能是,通过一组索引可能不同的Series构建一个DataFrame。 跟前面一样,这里也可以显式定义结果的索引(丢弃其余的数据): 时间和“最当前”数据选取 假设你有一个很长的盘中市场数据时间序列,现在希望抽取其中每天特定时间的价格数据。如果数据不规整(观测值没有精确地落在期望的时间点上),该怎么办?在实际工作当中,如果不够小心仔细的话,很容易导致错误的数据规整化。看看下面这个例子: 利用Python的datetime.time对象进行索引即可抽取出这些时间点上的值: 实际上,该操作用到了实例方法at_time(各时间序列以及类似的DataFrame对象都有): 还有一个between_time方法,它用于选取两个Time对象之间的值: 正如之前提到的那样,可能刚好就没有任何数据落在某个具体的时间上(比如上午10点)。这时,你可能会希望得到上午10点之前最后出现的那个值: 如果将一组Timestamp传入asof方法,就能得到这些时间点处(或其之前最近)的有效值(非NA)。例如,我们构造一个日期范围(每天上午10点),然后将其传入asof: 拼接多个数据源 在金融或经济领域中,还有几个经常出现的合并两个相关数据集的情况: ·在一个特定的时间点上,从一个数据源切换到另一个数据源。 ·用另一个时间序列对当前时间序列中的缺失值“打补丁”。 ·将数据中的符号(国家、资产代码等)替换为实际数据。 第一种情况:其实就是用pandas.concat将两个TimeSeries或DataFrame对象合并到一起: 其他:假设data1缺失了data2中存在的某个时间序列: combine_first可以引入合并点之前的数据,这样也就扩展了‘d’项的历史: DataFrame也有一个类似的方法update,它可以实现就地更新。如果只想填充空洞,则必须传入overwrite=False才行: 上面所讲的这些技术都可实现将数据中的符号替换为实际数据,但有时利用DataFrame的索引机制直接对列进行设置会更简单一些: 收益指数和累计收益 在金融领域中,收益(return)通常指的是某资产价格的百分比变化。一般计算两个时间点之间的累计百分比回报只需计算价格的百分比变化即可:对于其他那些派发股息的股票,要计算你在某只股票上赚了多少钱就比较复杂了。不过,这里所使用的已调整收盘价已经对拆分和股息做出了调整。不管什么样的情况,通常都会先算出一个收益指数,它是一个表示单位投资(比如1美元)收益的时间序列。 从收益指数中可以得出许多假设。例如,人们可以决定是否进行利润再投资。我们可以利用cumprod计算出一个简单的收益指数: 得到收益指数之后,计算指定时期内的累计收益就很简单了: 当然了,就这个简单的例子而言(没有股息也没有其他需要考虑的调整),上面的结果也能通过重采样聚合(这里聚合为时期)从日百分比变化中计算得出: 如果知道了股息的派发日和支付率,就可以将它们计入到每日总收益中,如下所示: 本篇文章为转载内容。原文链接:https://blog.csdn.net/geerniya/article/details/80534324。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-16 19:15:59
323
转载
Apache Pig
...逗号,然后定义了一个元组类型(order_id:int, customer_id:int, product_id:int, quantity:int)。dump命令则用于输出数据集的前几行,帮助我们验证数据是否正确加载。 示例2:数据过滤与聚合 接下来,假设我们想要找出每个客户的总订单数量: pig B = FOREACH A GENERATE customer_id, SUM(quantity) as total_quantity; C = GROUP B by 0; D = FOREACH C GENERATE key, SUM(total_quantity); dump D; 在这段脚本中,我们首先对原始数据集A进行处理,计算每个客户对应的总订单数量(步骤B),然后按照客户ID进行分组(步骤C),最后再次计算每组的总和(步骤D)。最终,dump D命令输出结果,显示了每个客户的ID及其总订单数量。 示例3:数据清洗与异常值处理 在处理真实世界的数据时,数据清洗是必不可少的步骤。例如,假设我们发现数据集中存在无效的订单ID: pig E = FILTER A BY order_id > 0; dump E; 通过FILTER语句,我们仅保留了order_id大于0的记录,这有助于排除无效数据,确保后续分析的准确性。 五、结语 Apache Pig的未来与挑战 随着大数据技术的不断发展,Apache Pig作为其生态中的重要组成部分,持续进化以适应新的需求。哎呀,你知道吗?Scripting Shell这个家伙,简直是咱们数据科学家们的超级帮手啊!它就像个神奇的魔法师,轻轻一挥,就把复杂的数据处理工作变得简单明了,就像是给一堆乱糟糟的线理了个顺溜。而且,它还能搭建起一座桥梁,让咱们这些数据科学家们能够更好地分享知识、交流心得,就像是在一场热闹的聚会里,大家围坐一起,畅所欲言,气氛超棒的!哎呀,你知道不?现在数据越来越多,越来越复杂,咱们得好好处理才行。那啥,Apache Pig这东西,以后要想做得更好,得解决几个大问题。首先,怎么让性能更上一层楼?其次,怎么让系统能轻松应对更多的数据?最后,怎么让用户用起来更顺手?这些可是Apache Pig未来的头等大事! 通过本文的探索,我们不仅了解了Apache Pig的基本原理和Scripting Shell的功能,还通过实际示例亲身体验了如何使用它来进行高效的数据处理。希望这些知识能够帮助你开启在大数据领域的新篇章,探索更多可能!
2024-09-30 16:03:59
95
繁华落尽
转载文章
.../ struct tuple4 / 描述一个地址端口对 , 它表示发送发IP 和端口以及接收方 IP 和端口 , 适用 TCP,UDP/ { u_short source; / 源 IP 地址的端口号/ u_short dest; / 目的 IP 地址的端口号/ u_int saddr; / 源 IP 地址 / u_int daddr; / 目的 IP 地址 / }; struct half_stream / 描述在 TCP 连接中一端的所有信息, 可以是客户端 , 也可以是服务端 / { char state; / 表示套接字的状态 , 也就是TCP 的状态 / char collect; / 可以表示有数据到达 , 此数据存放在data 成员中 , 也可以表示不存储此数据到 data中 , 此数据忽略 . 如果大于0 就存储 , 否则就忽略 / char collect_urg; / 可以表示有紧急数据到达 , 此数据就存放在urgdata 中 , 也可以表示不存储此数据到 urgdata中 , 此速数据忽略 . 如果大于0 就存储 , 否则就忽略 / char data; / 用户存储正常接受到的数据 / int offset; / 表示存储在 data 中数据的第一个字节的偏移量/ int count; / 表示从 TCP 连接开始已经存储到data 中的数据的字节数 / int count_new; / 有多少新的数据存储到 data 中, 如果为 0, 则表示没有新的数据到达 / int bufsize; int rmem_alloc; int urg_count; / 用来存储紧急数据 / u_int acked; u_int seq; u_int ack_seq; u_int first_data_seq; u_char urgdata; //存储紧急数据 u_char count_new_urg; / 表示有新的紧急数据到达 , 如果为0 表示没有新的紧急数据 / u_char urg_seen; //新的urg数据,不是以前重复的数据 u_int urg_ptr;/指向urg在流中的位置/ u_short window; u_char ts_on; u_char wscale_on; u_int curr_ts; u_int wscale; struct skbuff list; struct skbuff listtail; }; struct tcp_stream / 描述一个 TCP 连接的所有信息/ { struct tuple4 addr; char nids_state; struct lurker_node listeners; struct half_stream client; / 表示客户端信息 / struct half_stream server; / 表示服务端信息 / struct tcp_stream next_node; struct tcp_stream prev_node; int hash_index; struct tcp_stream next_time; struct tcp_stream prev_time; int read; struct tcp_stream next_free; }; struct nids_prm / 描述了 Libnids 的一些全局参数信息/ { int n_tcp_streams; / 表示哈西表大小 , 此哈西表用来存放tcp_stream 数据结构 , 默认值 1040.在同一时刻 Libnids 捕获的 TCP 数据包的最大个数必须是此参数值的3/4/ int n_hosts; / 表示哈西表的大小 , 此哈西表用来存储IP 碎片信息的 , 默认值为 256/ char device; / 表示网络接口 ,Libnids 将在此网络接口上捕获数据, 默认值为 NULL. 这样 Libnids将使用 pcap_lookupdev来查找可以用的网络接口 . 如果其值为 all, 表示捕获所有网络接口的数据/ char filename; / 表示用来存储网络数据的捕获文件 , 此文件的类型必须与 Libpcap 类型一致 , 如果设置了文件, 与此同时就应该设置 device 为 NULL,默认值为 NULL/ int sk_buff_size; / 表示的是数据接口 sk_buff 的大小 .sk_buff 是Linux 内核中一个重要的数据结构, 是用来进行数据包排队操作的 , 默认值为 168/ int dev_addon; / 表示在数据结构 sk_buff 中用于网络接口上信息的字节数. 如果是 -1( 默认值 ),那么 Libnids 会根据不同的网络接口进行修正 / void (syslog) (); / 是一个函数指针 , 默认值为nids_syslog() 函数 . 在 syslog函数中可以检测入侵攻击 , 如网络扫描攻击 , 也可以检测一些异常情况, 如无效 TCP 标记 / int syslog_level; / 表示日志等级 , 默认值是LOG_ALERT/ int scan_num_hosts; / 表示一个哈西表的大小 ,( 此哈西表用来存储端口扫描信息) 表示 Libnids 将要检测的同时扫描的端口数据 . 如果其值为 0,Libnids将不提供端口扫描功能 . 默认值 256/ int scan_delay; / 表示在扫描检测中 , 俩端口扫描的间隔时间, 以毫秒来计算 , 缺省值为 3000/ int scan_num_ports; / 表示相同源地址必须扫描的 TCP 端口数目 , 默认值为10/ void (no_mem) (char ); / 是一个函数指针 , 当Libnids 发生内存溢出时被调用/ int (ip_filter) (); / 是一个函数指针 , 此函数可以用来分析IP 数据包 , 当有 IP 数据包到达时 , 此函数就被调用. 如果此函数返回非零值 , 此数据包就被处理 ;如果返回零 , 此 IP 数据包就被丢弃. 默认值为 nids_ip_filter 函数 , 总是返回 1./ char pcap_filter; / 表示过滤规则 , 即Libpcap 的过滤规则 , 默认值为 NULL,表示捕获所有数据包 . 可以在此设置过滤规则 , 只捕获感兴趣的开发包/ int promisc; / 表示网卡模式 , 如果是非零, 就把此网卡设置为混杂模式 ; 否则 , 设为非混杂模式 . 默认值为1/ int one_loop_less; / 初始值为 0/ int pcap_timeout; / 表示捕获数据返回的时间 , 以毫秒计算. 实际上它表示的就是 Libpcap 函数中的 pcap_open_live函数的 timeout 参数 , 默认值 1024/ }; / 返回值 : 调用成功返回 1,失败返回 0 参 数 : 无 功 能 : 对 Libnids 初始化, 这是所有设计基于 Libnids 的程序最开始调用的函数 . 它的主要内容包括打开网络接口 , 打开文件 , 编译过滤规则 , 判断网络链路层类型, 进行必要的初始化工作 / int nids_init (void); / 返回值 : 无 参 数 : 回调函数名字 功 能 : 注册一个能够检测所有 IP 数据包的回调函数, 包括 IP 碎片 .e.g nids_register_ip_frag(ip_frag_function); void ip_frag_function(struct ip a_packet,int len) a_packet 表示接收的IP 数据包 len 表示接收的数据包长度 此回调函数可以检测所有的IP 数据包 , 包括 IP 碎片 / void nids_register_ip_frag (void ()); // / 返回值 : 无 参 数 : 回调函数名字 功 能 : 注册一个回调函数 , 此回调函数可以接收正常的IP 数据包 .e.g nids_register_ip_frag(ip_frag_function); void ip_frag_function(struct ip a_packet) a_packet 表示接收的IP 数据包 此回调函数可以接收正常的IP 数据包 , 并在此函数中对捕获数到的 IP数据包进行分析 . / void nids_register_ip (void ()); // / 返回值 : 无 参 数 : 回调函数 功 能 : 注册一个 TCP 连接的回调函数. 回调函数的类型定义如下 : void tcp_callback(struct tcp_stream ns,void param) ns 表示一个TCP 连接的所有信息 , param 表示要传递的参数信息 , 可以指向一个 TCP连接的私有数据 此回调函数接收的TCP 数据存放在 half_stream 的缓存中 , 应该马上取出来 ,一旦此回调函数返回 , 此数据缓存中存储的数据就不存在 了 .half_stream 成员 offset描述了被丢弃的数据字节数 . 如果不想马上取出来 , 而是等到存储一定数量的数据之后再取出来, 那么可 以使用函数nids_discard(struct tcp_stream ns, int num_bytes)来处理 . 这样回调函数返回时 ,Libnids 将丢弃缓存数据之前 的 num_bytes 字节的数据 .如果不调用 nids_discard()函数 , 那么缓存数据的字节应该为 count_new 字节 . 一般情况下, 缓存中的数据 应该是count-offset 字节 / void nids_register_tcp (void ()); / 返回值 : 无 参 数 : 回调函数 功 能 : 注册一个分析 UDP 协议的回调函数, 回调函数的类型定义如下 : void udp_callback(struct tuple4 addr,char buf,int len,struct ip iph) addr 表示地址端口信息buf 表示 UDP 协议负载的数据内容 len表是 UDP 负载数据的长度 iph 表示一个IP 数据包 , 包括 IP 首部 ,UDP 首部以及UDP 负载内容 / void nids_register_udp (void ()); / 返回值 : 无 参 数 : 表示一个 TCP 连接 功 能 : 终止 TCP 连接 . 它实际上是调用 Libnet的函数进行构造数据包 , 然后发送出去 / void nids_killtcp (struct tcp_stream ); / 返回值 : 无 参 数 : 参数 1 一个 TCP 连接 参数 2 个数 功 能 : 丢弃参数 2 字节 TCP 数据 , 用于存储更多的数据 / void nids_discard (struct tcp_stream , int); / 返回值 : 无 参 数 : 无 功 能 : 运行 Libnids, 进入循环捕获数据包状态. 它实际上是调用 Libpcap 函数 pcap_loop()来循环捕获数据包 / void nids_run (void); / 返回值 : 调用成功返回文件描述符 ,失败返回 -1 参 数 : 无 功 能 : 获得文件描述符号 / int nids_getfd (void); / 返回值 : 调用成功返回个数 ,失败返回负数 参 数 : 表示捕获数据包的个数 功 能 : 调用 Libpcap 中的捕获数据包函数pcap_dispatch() / int nids_dispatch (int); / 返回值 : 调用成功返回 1,失败返回 0 参 数 : 无 功 能 : 调用 Libpcap 中的捕获数据包函数pcap_next() / int nids_next (void); extern struct nids_prm nids_params; /libnids.c定以了一个全部变量 , 其定义和初始值在 nids_params/ extern char nids_warnings[]; extern char nids_errbuf[]; extern struct pcap_pkthdr nids_last_pcap_header; struct nids_chksum_ctl { / 描述的是计算校验和 , 用于决定是否计算校验和/ u_int netaddr; / 表示地址 / u_int mask; / 表示掩码 / u_int action; / 表示动作 , 如果是NIDS_DO_CHKSUM, 表示计算校验和; 如果是 NIDS_DONT_CHKSUM, 表示不计算校验和 / u_int reserved; / 保留未用 / }; / 返回值 : 无 参 数 : 参数 1 表示 nids_chksum_ctl 列表 参数 2 表示列表中的个数 功 能 : 决定是否计算校验和 . 它是根据数据结构nids_chksum_ctl 中的action 进行决定的 , 如果所要计算的对象不在列表中 , 则必须都要计算校验和 / extern void nids_register_chksum_ctl(struct nids_chksum_ctl , int); endif / _NIDS_NIDS_H / 本篇文章为转载内容。原文链接:https://blog.csdn.net/xieqb/article/details/7681968。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-02-08 17:36:31
306
转载
转载文章
...提供一致的事务管理和元组可见性控制。 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
转载
转载文章
...指定hash方法(5元组,OpenFlow1.5+) ovs-ofctl -O OpenFlow15 add-group br0 group_id=3,type=select,selection_method=hash,fields=ip_src,bucket=output:2,bucket=output:3 4.删除group表 ovs-ofctl -O OpenFlow13 del-groups br0 group_id=2 5.创建流表 ovs-ofctl -O OpenFlow13 add-flow br0 in_port=1,actions=group:2 goto table配置 数据流先从table0开始匹配,如actions有goto_table,再进行后续table的匹配,实现多级流水线,如需使用goto table,则创建流表时,指定table id,范围为0-255,不指定则默认为table0 1.在table0中添加一条流表条目 ovs-ofctl add-flow br0 table=0,in_port=1,actions=goto_table=1 2.在table1中添加一条流表条目 ovs-ofctl add-flow br0 table=1,ip,nw_dst=10.10.0.0/16,actions=output:2 tunnel配置 如需配置tunnel,必需确保当前系统对各tunnel的remote ip网络可达 gre 1.创建一个gre接口,并且指定端口id=1001 ovs-vsctl add-port br0 gre1 -- set Interface gre1 type=gre options:remote_ip=1.1.1.1 ofport_request=1001 2.可选选项 将tos或者ttl在隧道上继承,并将tunnel id设置成123 ovs-vsctl set Interface gre1 options:tos=inherit options:ttl=inherit options:key=123 3.创建关于gre流表 封装gre转发 ovs-ofctl add-flow br0 ip,in_port=1,nw_dst=10.10.0.0/16,actions=output:1001 解封gre转发 ovs-ofctl add-flow br0 in_port=1001,actions=output:1 vxlan 1.创建一个vxlan接口,并且指定端口id=2001 ovs-vsctl add-port br0 vxlan1 -- set Interface vxlan1 type=vxlan options:remote_ip=1.1.1.1 ofport_request=2001 2.可选选项 将tos或者ttl在隧道上继承,将vni设置成123,UDP目的端为设置成8472(默认为4789) ovs-vsctl set Interface vxlan1 options:tos=inherit options:ttl=inherit options:key=123 options:dst_port=8472 3.创建关于vxlan流表 封装vxlan转发 ovs-ofctl add-flow br0 ip,in_port=1,nw_dst=10.10.0.0/16,actions=output:2001 解封vxlan转发 ovs-ofctl add-flow br0 in_port=2001,actions=output:1 sflow配置 1.对网桥br0进行sflow监控 agent: 与collector通信所在的网口名,通常为管理口 target: collector监听的IP地址和端口,端口默认为6343 header: sFlow在采样时截取报文头的长度 polling: 采样时间间隔,单位为秒 ovs-vsctl -- --id=@sflow create sflow agent=eth0 target=\"10.0.0.1:6343\" header=128 sampling=64 polling=10 -- set bridge br0 sflow=@sflow 2.查看创建的sflow ovs-vsctl list sflow 3.删除对应的网桥sflow配置,参数为sFlow UUID ovs-vsctl remove bridge br0 sflow 7b9b962e-fe09-407c-b224-5d37d9c1f2b3 4.删除网桥下所有sflow配置 ovs-vsctl -- clear bridge br0 sflow 1 QoS配置 ingress policing 1.配置ingress policing,对接口eth0入流限速10Mbps ovs-vsctl set interface eth0 ingress_policing_rate=10000 ovs-vsctl set interface eth0 ingress_policing_burst=8000 2.清除相应接口的ingress policer配置 ovs-vsctl set interface eth0 ingress_policing_rate=0 ovs-vsctl set interface eth0 ingress_policing_burst=0 3.查看接口ingress policer配置 ovs-vsctl list interface eth0 4.查看网桥支持的Qos类型 ovs-appctl qos/show-types br0 端口镜像配置 1.配置eth0收到/发送的数据包镜像到eth1 ovs-vsctl -- set bridge br0 mirrors=@m \ -- --id=@eth0 get port eth0 \ -- --id=@eth1 get port eth1 \ -- --id=@m create mirror name=mymirror select-dst-port=@eth0 select-src-port=@eth0 output-port=@eth1 2.删除端口镜像配置 ovs-vsctl -- --id=@m get mirror mymirror -- remove bridge br0 mirrors @m 3.清除网桥下所有端口镜像配置 ovs-vsctl clear bridge br0 mirrors 4.查看端口镜像配置 ovs-vsctl get bridge br0 mirrors Open vSwitch中有多个命令,分别有不同的作用,大致如下: ovs-vsctl用于控制ovs db ovs-ofctl用于管理OpenFlow switch 的 flow ovs-dpctl用于管理ovs的datapath ovs-appctl用于查询和管理ovs daemon 转载于:https://www.cnblogs.com/liuhongru/p/10336849.html 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_30876945/article/details/99916308。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-06-08 17:13:19
294
转载
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
pgrep process_pattern
- 根据进程名模式搜索进程ID。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"