Spark2.3(三十七):Stream join Stream(res文件每天更新一份)

kafka测试数据生成:

1package com.dx.kafka; 2 3import java.util.Properties; 4import java.util.Random; 5 6import org.apache.kafka.clients.producer.Producer; 7import org.apache.kafka.clients.producer.ProducerRecord; 8 9public class KafkaProducer { 10 public static void main(String[] args) throws InterruptedException { 11 Properties props = new Properties(); 12 props.put("bootstrap.servers", "192.168.0.141:9092,192.168.0.142:9092,192.168.0.143:9092,192.168.0.144:9092"); 13 props.put("acks", "all"); 14 props.put("retries", 0); 15 props.put("batch.size", 16384); 16 props.put("linger.ms", 1); 17 props.put("buffer.memory", 33554432); 18 props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); 19 props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); 20 Producer<String, String> producer = new org.apache.kafka.clients.producer.KafkaProducer(props); 21 int i = 0; 22 Random random=new Random(); 23 while (true) { 24 i++; 25 producer.send(new ProducerRecord<String, String>("my-topic", "key-" + Integer.toString(i), 26 i%3+","+random.nextInt(100))); 27 System.out.println(i); 28 Thread.sleep(1000); 29 30 if(i%100==0) { 31 Thread.sleep(60*1000); 32 } 33 } 34 // producer.close(); 35 36 } 37}

Stream join Stream测试代码:

要求:使用spark structured streaming实时读取kafka中的数据,kafka中的数据包含字段int_id;kafka上数据需要关联资源信息(通过kafka的int_id与资源的int_id进行关联),同时要求资源每天都更新。

使用spark structured streaming实时读取kafka中的数据

1Dataset<Row> linesDF = this.sparkSession.readStream()// 2 .format("kafka")// 3 .option("failOnDataLoss", false)// 4 .option("kafka.bootstrap.servers", "192.168.0.141:9092,192.168.0.142:9092,192.168.0.143:9092,192.168.0.144:9092")// 5 .option("subscribe", "my-topic")// 6 .option("startingOffsets", "earliest")// 7 .option("maxOffsetsPerTrigger", 10)// 8 .load(); 9 10 StructType structType = new StructType(); 11 structType = structType.add("int_id", DataTypes.StringType, false); 12 structType = structType.add("rsrp", DataTypes.StringType, false); 13 structType = structType.add("mro_timestamp", DataTypes.TimestampType, false); 14 ExpressionEncoder<Row> encoder = RowEncoder.apply(structType); 15 Dataset<Row> mro = linesDF.select("value").as(Encoders.STRING()).map(new MapFunction<String, Row>() { 16 private static final long serialVersionUID = 1L; 17 18 @Override 19 public Row call(String t) throws Exception { 20 List<Object> values = new ArrayList<Object>(); 21 String[] fields = t.split(","); 22 values.add(fields.length >= 1 ? fields[0] : "null"); 23 values.add(fields.length >= 2 ? fields[1] : "null"); 24 values.add(new Timestamp(new Date().getTime())); 25 26 return RowFactory.create(values.toArray()); 27 } 28 }, encoder); 29 mro=mro.withWatermark("mro_timestamp", "15 minutes"); 30 mro.printSchema();

加载资源信息

1StructType resulStructType = new StructType(); 2 resulStructType = resulStructType.add("int_id", DataTypes.StringType, false); 3 resulStructType = resulStructType.add("enodeb_id", DataTypes.StringType, false); 4 resulStructType = resulStructType.add("res_timestamp", DataTypes.TimestampType, false); 5 ExpressionEncoder<Row> resultEncoder = RowEncoder.apply(resulStructType); 6 Dataset<Row> resDs = sparkSession.readStream().option("maxFileAge", "1ms").textFile(resourceDir) 7 .map(new MapFunction<String, Row>() { 8 private static final long serialVersionUID = 1L; 9 10 @Override 11 public Row call(String value) throws Exception { 12 String[] fields = value.split(","); 13 Object[] objItems = new Object[3]; 14 objItems[0] = fields[0]; 15 objItems[1] = fields[1]; 16 objItems[2] = Timestamp.valueOf(fields[2]); 17 18 return RowFactory.create(objItems); 19 } 20 }, resultEncoder); 21 resDs = resDs.withWatermark("res_timestamp", "1 seconds"); 22 resDs.printSchema();

kafka上数据与资源关联

关联条件int_id相同,同时要求res.timestamp<=mro.timestmap & res.timestamp<(mro.timestmap-1天)

res如果放入broadcast经过测试发现也是可行的。

1// JavaSparkContext jsc = 2 // JavaSparkContext.fromSparkContext(sparkSession.sparkContext()); 3 Dataset<Row> cellJoinMro = mro.as("t10")// 4 .join(resDs.as("t11"),// jsc.broadcast(resDs).getValue() 5 functions.expr("t11.int_id=t10.int_id "// 6 + "and t11.res_timestamp<=t10.mro_timestamp "// 7 + "and timestamp_diff(t11.res_timestamp,t10.mro_timestamp,'>','-86400000')"),// 8 "left_outer")// 9 .selectExpr("t10.int_id", "t10.rsrp", "t11.enodeb_id", "t10.mro_timestamp", "t11.res_timestamp"); 10 11 StreamingQuery query = cellJoinMro.writeStream().format("console").outputMode("update") // 12 .trigger(Trigger.ProcessingTime(1, TimeUnit.MINUTES))// 13 .start();

udf:timestamp_diff定义

1sparkSession.udf().register("timestamp_diff", new UDF4<Timestamp, Timestamp, String, String, Boolean>() { 2 private static final long serialVersionUID = 1L; 3 4 @Override 5 public Boolean call(Timestamp t1, Timestamp t2, String operator, String intervalMsStr) throws Exception { 6 long diffValue=t1.getTime()-t2.getTime(); 7 long intervalMs=Long.valueOf(intervalMsStr); 8 9 if(operator.equalsIgnoreCase(">")){ 10 return diffValue>intervalMs; 11 }else if(operator.equalsIgnoreCase(">=")){ 12 return diffValue>=intervalMs; 13 }else if(operator.equalsIgnoreCase("<")){ 14 return diffValue<intervalMs; 15 }else if(operator.equalsIgnoreCase("<=")){ 16 return diffValue<=intervalMs; 17 }else if(operator.equalsIgnoreCase("=")){ 18 return diffValue==intervalMs; 19 }else{ 20 throw new RuntimeException("unknown error"); 21 } 22 } 23 },DataTypes.BooleanType);

如果删除资源历史数据,不会导致正在运行的程序抛出异常;当添加新文件到res hdfs路径下时,可以自动被加载进来。

备注:要求必须每天资源文件只能有一份,否则会导致kafka上数据关联后结果重复,同时,res上的每天的文件中包含timestmap字段格式都为yyyy-MM-dd 00:00:00。

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )