package com.mashibing.flinkjava.code.reporters;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
public class ReportDemo {
public static void main(String[] args) throws Exception {
// 1. 创建 Configuration 并注入 PushGateway Reporter 配置
Configuration conf = new Configuration();
// 启用名为 "promgateway" 的 reporter
conf.setString("metrics.reporters", "promgateway");
// 指定 Reporter 工厂类(Flink 1.15+ 推荐写法)
conf.setString("metrics.reporter.promgateway.factory.class",
"org.apache.flink.metrics.prometheus.PrometheusPushGatewayReporterFactory");
// PushGateway 服务地址(请替换为你实际的 IP/域名 和端口)
conf.setString("metrics.reporter.promgateway.host", "localhost");
conf.setString("metrics.reporter.promgateway.port", "9091");
// 作业名称(在 PushGateway 中作为分组标识)
conf.setString("metrics.reporter.promgateway.jobName", "report-demo-job");
// 是否在作业名后添加随机后缀(避免多次运行时指标覆盖,本地调试建议 true)
conf.setString("metrics.reporter.promgateway.randomJobNameSuffix", "true");
// 作业关闭时是否删除 PushGateway 上的对应指标
conf.setString("metrics.reporter.promgateway.deleteOnShutdown", "true");
// 2. 使用带配置的环境创建方式
StreamExecutionEnvironment env = StreamExecutionEnvironment
.createLocalEnvironmentWithWebUI(conf);
env.setParallelism(1);
env.disableOperatorChaining();
StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
String sourceDDL = "CREATE TABLE Bid (\n" +
" user_id BIGINT,\n" +
" price DECIMAL(10, 2),\n" +
" bid_time AS TIMESTAMPADD(SECOND, user_id, TO_TIMESTAMP('2026-01-01 00:00:00')),\n" +
" WATERMARK FOR bid_time AS bid_time - INTERVAL '1' SECOND\n" +
") WITH (\n" +
" 'connector' = 'datagen',\n" +
" 'rows-per-second' = '1',\n" +
" 'fields.price.min' = '10',\n" +
" 'fields.price.max' = '20',\n" +
" 'fields.user_id.kind' = 'sequence',\n" +
" 'fields.user_id.start' = '0',\n" +
" 'fields.user_id.end' = '86400'\n" +
")";
tableEnv.executeSql(sourceDDL);
String windowQuery = "SELECT \n" +
" window_start,\n" +
" window_end,\n" +
" AVG(CASE \n" +
" WHEN price > 0 \n" +
" THEN price - 0.245 \n" +
" END) AS avg_price\n" +
"FROM table (\n" +
" TUMBLE(TABLE Bid, DESCRIPTOR(bid_time), INTERVAL '5' SECOND))\n" +
"GROUP BY window_start, window_end";
tableEnv.executeSql(
"CREATE TABLE window_results (\n" +
" window_start TIMESTAMP(3),\n" +
" window_end TIMESTAMP(3),\n" +
" avg_price DECIMAL(10, 2)\n" +
") WITH ('connector' = 'print')"
);
tableEnv.executeSql("INSERT INTO window_results " + windowQuery);
}
}