首页 > 应用开发 > Java > 如何使用Docker内的kafka服务
For a tutorial how to write a Flink streaming application, check the * tutorials and examples on the Flink Website. * *
To package your application into a JAR file for execution, run * 'mvn clean package' on the command line. * *
If you change the name of the main class (with the public static void main(String[] args)) * method, change the respective entry in the POM.xml file (simply search for 'mainClass'). */ public class StreamingJob { public static void main(String[] args) throws Exception { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.enableCheckpointing(5000); // 要设置启动检查点 env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); Properties props = new Properties(); props.setProperty("bootstrap.servers", "kafka1:9092"); props.setProperty("group.id", "flink-group"); //数据源配置,是一个kafka消息的消费者 FlinkKafkaConsumer011 consumer = new FlinkKafkaConsumer011<>("topic001", new SimpleStringSchema(), props); //增加时间水位设置类 consumer.assignTimestampsAndWatermarks(new AssignerWithPunctuatedWatermarks (){ @Override public long extractTimestamp(String element, long previousElementTimestamp) { return JSONHelper.getTimeLongFromRawMessage(element); } @Nullable @Override public Watermark checkAndGetNextWatermark(String lastElement, long extractedTimestamp) { if (lastElement != null) { return new Watermark(JSONHelper.getTimeLongFromRawMessage(lastElement)); } return null; } }); env.addSource(consumer) //将原始消息转成Tuple2对象,保留用户名称和访问次数(每个消息访问次数为1) .flatMap((FlatMapFunction>) (s, collector) -> { SingleMessage singleMessage = JSONHelper.parse(s); if (null != singleMessage) { collector.collect(new Tuple2<>(singleMessage.getName(), 1L)); } }) //以用户名为key .keyBy(0) //时间窗口为2秒 .timeWindow(Time.seconds(2)) //将每个用户访问次数累加起来 .apply((WindowFunction, Tuple2, Tuple, TimeWindow>) (tuple, window, input, out) -> { long sum = 0L; for (Tuple2 record: input) { sum += record.f1; } Tuple2 result = input.iterator().next(); result.f1 = sum; out.collect(result); }) //输出方式是STDOUT .print(); env.execute("Flink-Kafka demo"); } } ``` - 在pom.xml所在文件夹执行以下命令打包: ```shell mvn clean package -Dmaven.test.skip=true -U ``` - 打包成功后,会在target目录下生成文件**flinkkafkademo-1.0-SNAPSHOT.jar,将此文件提交到Flinkserver上,如下图:  - 点击下图红框中的"Upload"按钮:  - 如下图,选中刚刚上传的文件,填写类名,再点击"Submit"按钮即可启动Job:  - 如下图,在Overview页面可见正在运行的任务:  - 现在所有服务都准备完毕,可以生产消息验证了; ### 在机器192.168.1.104上发起压力测试,产生大量消息 - 登录部署了Apache Bench的机器,执行以下命令: ```shell ab -n 10000 -c 2 http://192.168.1.101:8080/send/Jack/hello ``` 192.168.1.101是消息生产者的web服务的地址,上述命令发起了并发数为2的压力测试,一共会发起一万次请求; - 压力测试完毕后,在Flink的Task Managers页面的Stdout页可以见到实时计算的统计数据,如下图:  - 至此,Flink消费kafka消息的实战就全部完成了,本次实战从消息产生到实时处理全部实现,希望在您构建基于kafak的实时计算环境时可以提供一些参考; ### 欢迎关注ITpub:程序员欣宸 > [学习路上,你不孤单,欣宸原创一路相伴...](http://blog.itpub.net/70017844/)
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70017844/viewspace-2907800/ ,如需转载,请注明出处,否则将追究法律责任。
注册时间:2022-05-16