用一个接地气的案例来介绍如何实时计算 UV 数据。大家都知道,在 ToC 的互联网公司,UV 是一个很重要的指标,对于老板、商务、运营的及时决策会产生很大的影响,笔者在电商公司,目前主要的工作就是计算 UV、销售等各类实时数据,体验就特别深刻, 因此就用一个简单demo 演示如何用 Flink SQL 消费 Kafka 中的 PV 数据,实时计算出 UV 指标后写入 Hbase。
Kafka 源数据解析输入标题
PV 数据来源于埋点数据经 FileBeat 上报清洗后,以 ProtoBuffer 格式写入下游 Kafka,消费时第一步要先反序列化 PB 格式的数据为 Flink 能识别的 Row 类型,因此也就需要自定义实现 DeserializationSchema 接口,具体如下代码, 这里只抽取计算用到的 PV 的 mid、事件时间 time_local,并从其解析得到 log_date 字段:
public class PageViewDeserializationSchema implements DeserializationSchema<Row> {
public static final Logger LOG = LoggerFactory.getLogger(PageViewDeserializationSchema.class);
protected SimpleDateFormat dayFormatter;
private final RowTypeInfo rowTypeInfo;
public PageViewDeserializationSchema(RowTypeInfo rowTypeInfo){
dayFormatter = new SimpleDateFormat("yyyyMMdd", Locale.UK);
this.rowTypeInfo = rowTypeInfo;
}
@Override
public Row deserialize(byte[] message) throws IOException {
Row row = new Row(rowTypeInfo.getArity());
MobilePage mobilePage = null;
try {
mobilePage = MobilePage.parseFrom(message);
String mid = mobilePage.getMid();
row.setField(0, mid);
Long timeLocal = mobilePage.getTimeLocal();
String logDate = dayFormatter.format(timeLocal);
row.setFiel