千家信息网

flink中如何使用set实时计算当天网站uv

发表于:2024-09-22 作者:千家信息网编辑
千家信息网最后更新 2024年09月22日,flink中如何使用set实时计算当天网站uv,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。背景对于web网站,我们一般会有这样的需
千家信息网最后更新 2024年09月22日flink中如何使用set实时计算当天网站uv

flink中如何使用set实时计算当天网站uv,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

背景

对于web网站,我们一般会有这样的需求,实时的计算出来当天网站的uv,尽可能快的展示出来。今天我们就讲一下基于java的set集合做一下实时uv的统计。

简易需求:

  • 实时计算出当天零点截止到当前时间各个端(android,ios,h6)下的uv
  • 每秒钟更新一次统计结果

案例讲解

模拟source

首先我们模拟生成一下最简单的数据,生成一个flink的二元组Tuple2.分别表示分类和用户id


public static class MySource implements SourceFunction>{
private volatile boolean isRunning = true;
String category[] = {"Android", "IOS", "H5"};
@Override
public void run(SourceContext> ctx) throws Exception{
while (isRunning){
Thread.sleep(10);
//具体是哪个端的用户
String type = category[(int) (Math.random() * (category.length))];
//随机生成10000以内的int类型数据作为userid
int userid = (int) (Math.random() * 10000);
ctx.collect(Tuple2.of(type, userid));
}
}
@Override
public void cancel(){
isRunning = false;
}
}

定义窗口

接下来我们定义一个周期是一天的滑动窗口,因为我们要每秒钟输出窗口的数据,所以我们紧接着窗口定义了一个1秒的触发器。


DataStream> dataStream = env.addSource(new MySource());
dataStream.keyBy(0).window(TumblingProcessingTimeWindows.of(Time.days(1), Time.hours(-8)))
.trigger(ContinuousProcessingTimeTrigger.of(Time.seconds(1)))
.aggregate(new MyAggregate(),new WindowResult())
.print();

自定义聚合算子

接下来我们自定义一个聚合算子来实现该功能。

对于聚合算子的理解可以参考这个文章:

https://mp.weixin.qq.com/s/ZCWexNGzhSchRpxipa1x-g

 public static class MyAggregate
implements AggregateFunction,Set,Integer>{
@Override
public Set createAccumulator(){
return new HashSet<>();
}
@Override
public Set add(Tuple2 value, Set accumulator){
accumulator.add(value.f1);
return accumulator;
}
@Override
public Integer getResult(Set accumulator){
return accumulator.size();
}
@Override
public Set merge(Set a, Set b){
a.addAll(b);
return a;
}
}

处理输出结果

我们这里将结果输出到控制台,实际的生产中我们可以将数据写入redis或者hbase等。


1> Result{, dateTime='2020-06-21 19:23:30'type='IOS', uv=136}
2> Result{, dateTime='2020-06-21 19:23:30'type='Android', uv=150}
1> Result{, dateTime='2020-06-21 19:23:30'type='H5', uv=134}
1> Result{, dateTime='2020-06-21 19:23:31'type='IOS', uv=164}
2> Result{, dateTime='2020-06-21 19:23:31'type='Android', uv=177}
1> Result{, dateTime='2020-06-21 19:23:31'type='H5', uv=167}
2> Result{, dateTime='2020-06-21 19:23:32'type='Android', uv=205}
1> Result{, dateTime='2020-06-21 19:23:32'type='IOS', uv=193}
1> Result{, dateTime='2020-06-21 19:23:32'type='H5', uv=198}

关于flink中如何使用set实时计算当天网站uv问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。

0