支付寬表的目的,最主要的原因是支付表沒有到訂單明細,支付金額沒有細分到商品上, 沒有辦法統計商品級的支付狀況。 所以本次寬表的核心就是要把支付表的資訊與訂單明細關聯上。
解決方案有兩個
一個是把訂單明細表(或者寬表)輸出到 Hbase 上,在支付寬表計算時查詢 hbase, 這相當於把訂單明細作為一種維度進行管理。
一個是用流的方式接收訂單明細,然後用雙流 join 方式進行合併。因為訂單與支付產 生有一定的時差。所以必須用 intervalJoin 來管理流的狀態時間,保證當支付到達時訂 單明細還儲存在狀態中。
支付相關實體類
import lombok.Data;
import java.math.BigDecimal;
/**
* @author zhangbaohpu
* @date 2021/12/25 10:08
* @desc 支付實體類
*/
@Data
public class PaymentInfo {
Long id;
Long order_id;
Long user_id;
BigDecimal total_amount;
String subject;
String payment_type;
String create_time;
String callback_time;
}
PaymentWide.java:支付寬表實體類
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.beanutils.BeanUtils;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
/**
* @author zhangbaohpu
* @date 2021/12/25 10:10
* @desc 支付寬表實體類
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PaymentWide {
Long payment_id;
String subject;
String payment_type;
String payment_create_time;
String callback_time;
Long detail_id;
Long order_id ;
Long sku_id;
BigDecimal order_price ;
Long sku_num ;
String sku_name;
Long province_id;
String order_status;
Long user_id;
BigDecimal total_amount;
BigDecimal activity_reduce_amount;
BigDecimal coupon_reduce_amount;
BigDecimal original_total_amount;
BigDecimal feight_fee;
BigDecimal split_feight_fee;
BigDecimal split_activity_amount;
BigDecimal split_coupon_amount;
BigDecimal split_total_amount;
String order_create_time;
String province_name;//查詢維表得到
String province_area_code;
String province_iso_code;
String province_3166_2_code;
Integer user_age ;
String user_gender;
Long spu_id; //作為維度資料 要關聯進來
Long tm_id;
Long category3_id;
String spu_name;
String tm_name;
String category3_name;
public PaymentWide(PaymentInfo paymentInfo, OrderWide orderWide){
mergeOrderWide(orderWide);
mergePaymentInfo(paymentInfo);
}
public void mergePaymentInfo(PaymentInfo paymentInfo ) {
if (paymentInfo != null) {
try {
BeanUtils.copyProperties(this,paymentInfo);
payment_create_time=paymentInfo.create_time;
payment_id = paymentInfo.id;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
public void mergeOrderWide(OrderWide orderWide ) {
if (orderWide != null) {
try {
BeanUtils.copyProperties(this,orderWide);
order_create_time=orderWide.create_time;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
支付寬表主程式
目前還沒有任何計算,仍然放在dwm層
在dwm包下建立PaymentWideApp.java任務類
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.zhangbao.gmall.realtime.bean.OrderWide;
import com.zhangbao.gmall.realtime.bean.PaymentInfo;
import com.zhangbao.gmall.realtime.bean.PaymentWide;
import com.zhangbao.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.runtime.state.filesystem.FsStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.util.Collector;
import java.time.Duration;
/**
* @author zhangbaohpu
* @date 2021/12/25 10:16
* @desc 支付寬表
*/
public class PaymentWideApp {
public static void main(String[] args) {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
//新增並行度
env.setParallelism(4);
//設定檢查點
// env.enableCheckpointing(5000, CheckpointingMode.EXACTLY_ONCE);
// env.getCheckpointConfig().setCheckpointTimeout(60000);
// env.setStateBackend(new FsStateBackend("hdfs://hadoop101:9000/gmall/flink/checkpoint/paymentWide"));
// //指定哪個使用者讀取hdfs檔案
// System.setProperty("HADOOP_USER_NAME","zhangbao");
//設定kafka主題及消費者組
String paymentInfoTopic = "dwd_payment_info";
String orderWideTopic = "dwm_order_wide";
String paymentWideTopic = "dwm_payment_wide";
String paymentWideGroup = "paymentWideGroup";
//獲取支付資訊
FlinkKafkaConsumer<String> paymentInfo = MyKafkaUtil.getKafkaSource(paymentInfoTopic, paymentWideGroup);
DataStreamSource<String> paymentInfoJsonStrDs = env.addSource(paymentInfo);
//獲取訂單寬表資訊
FlinkKafkaConsumer<String> orderWide = MyKafkaUtil.getKafkaSource(orderWideTopic, paymentWideGroup);
DataStreamSource<String> orderWideJsonStrDs = env.addSource(orderWide);
//轉換格式
SingleOutputStreamOperator<PaymentInfo> paymentJsonDs = paymentInfoJsonStrDs.map(paymentInfoStr -> JSON.parseObject(paymentInfoStr, PaymentInfo.class));
SingleOutputStreamOperator<OrderWide> orderWideJsonDs = orderWideJsonStrDs.map(orderWideStr -> JSON.parseObject(orderWideStr, OrderWide.class));
paymentJsonDs.print("payment info >>>");
orderWideJsonDs.print("order wide >>>");
//指定事件時間欄位
SingleOutputStreamOperator<PaymentInfo> paymentInfoWithWaterMarkDs = paymentJsonDs.assignTimestampsAndWatermarks(
WatermarkStrategy.<PaymentInfo>forBoundedOutOfOrderness(Duration.ofSeconds(3))
.withTimestampAssigner(new SerializableTimestampAssigner<PaymentInfo>() {
@Override
public long extractTimestamp(PaymentInfo paymentInfo, long l) {
return DateUtil.parse(paymentInfo.getCallback_time(), DatePattern.NORM_DATETIME_PATTERN).getTime();
}
})
);
SingleOutputStreamOperator<OrderWide> orderWideWithWaterMarkDs = orderWideJsonDs.assignTimestampsAndWatermarks(
WatermarkStrategy.<OrderWide>forBoundedOutOfOrderness(Duration.ofSeconds(3))
.withTimestampAssigner(new SerializableTimestampAssigner<OrderWide>() {
@Override
public long extractTimestamp(OrderWide orderWide, long l) {
return DateUtil.parse(orderWide.getCreate_time(), DatePattern.NORM_DATETIME_PATTERN).getTime();
}
})
);
//分組
KeyedStream<PaymentInfo, Long> paymentInfoKeyedDs = paymentInfoWithWaterMarkDs.keyBy(payInfoObj -> payInfoObj.getOrder_id());
KeyedStream<OrderWide, Long> orderWideKeyedDs = orderWideWithWaterMarkDs.keyBy(orderWideObj -> orderWideObj.getOrder_id());
paymentInfoKeyedDs.print("paymentInfoKeyedDs >>>");
orderWideKeyedDs.print("orderWideKeyedDs >>>");
//雙流join,用支付資料關聯訂單資料
SingleOutputStreamOperator<PaymentWide> paymentWideObjDs = paymentInfoKeyedDs.intervalJoin(orderWideKeyedDs)
.between(Time.seconds(-1800), Time.seconds(1800))
.process(new ProcessJoinFunction<PaymentInfo, OrderWide, PaymentWide>() {
@Override
public void processElement(PaymentInfo paymentInfo, OrderWide orderWide, ProcessJoinFunction<PaymentInfo, OrderWide, PaymentWide>.Context context, Collector<PaymentWide> collector) throws Exception {
System.out.println(paymentInfo);
System.out.println(orderWide);
collector.collect(new PaymentWide(paymentInfo, orderWide));
}
});
//將資料流轉換為json
SingleOutputStreamOperator<String> paymentWideDs = paymentWideObjDs.map(paymentWide -> JSON.toJSONString(paymentWide));
paymentWideDs.print("payment wide json >>> ");
//傳送到kafka
FlinkKafkaProducer<String> kafkaSink = MyKafkaUtil.getKafkaSink(paymentWideTopic);
paymentWideDs.addSink(kafkaSink);
try {
env.execute("payment wide task");
} catch (Exception e) {
e.printStackTrace();
}
}
}
到這裡,支付寬表的操作就完成了。
專案地址:https://github.com/zhangbaohpu/gmall-flink-parent/tree/master/gmall-realtime
總結
DWM 層部分的程式碼主要的責任,是通過計算把一種明細轉變為另一種明細以應對後續的統計。學完本階段內容要求掌握
-
學會利用狀態(state)進行去重操作。(需求:UV 計算)
-
學會利用 CEP 可以針對一組資料進行篩選判斷。需求:跳出行為計算
-
學會使用 intervalJoin 處理流 join
-
學會處理維度關聯,並通過快取和非同步查詢對其進行效能優化。