1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
| package com.bigdata.flink;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.apache.flink.api.common.serialization.SimpleStringSchema; import org.apache.flink.api.common.state.BroadcastState; import org.apache.flink.api.common.state.MapStateDescriptor; import org.apache.flink.api.common.state.ReadOnlyBroadcastState; import org.apache.flink.api.common.typeinfo.Types; import org.apache.flink.api.java.tuple.*; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.configuration.Configuration; import org.apache.flink.runtime.state.StateBackend; import org.apache.flink.runtime.state.filesystem.FsStateBackend; import org.apache.flink.shaded.guava18.com.google.common.collect.Maps; import org.apache.flink.streaming.api.CheckpointingMode; import org.apache.flink.streaming.api.datastream.*; import org.apache.flink.streaming.api.environment.CheckpointConfig; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.ProcessFunction; import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction; import org.apache.flink.streaming.api.functions.source.RichSourceFunction; import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer010; import org.apache.flink.util.Collector;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.HashMap; import java.util.Map; import java.util.Properties;
@Slf4j public class TestBroadcastState { public static void main(String[] args) throws Exception{
ParameterTool fromArgs = ParameterTool.fromArgs(args); ParameterTool parameterTool = ParameterTool.fromPropertiesFile(fromArgs.getRequired("applicationProperties"));
String checkpointDirectory = parameterTool.getRequired("checkpointDirectory"); long checkpointSecondInterval = parameterTool.getLong("checkpointSecondInterval");
String fromKafkaBootstrapServers = parameterTool.getRequired("fromKafka.bootstrap.servers"); String fromKafkaGroupID = parameterTool.getRequired("fromKafka.group.id"); String fromKafkaTopic = parameterTool.getRequired("fromKafka.topic");
String fromMysqlHost = parameterTool.getRequired("fromMysql.host"); int fromMysqlPort = parameterTool.getInt("fromMysql.port"); String fromMysqlDB = parameterTool.getRequired("fromMysql.db"); String fromMysqlUser = parameterTool.getRequired("fromMysql.user"); String fromMysqlPasswd = parameterTool.getRequired("fromMysql.passwd"); int fromMysqlSecondInterval = parameterTool.getInt("fromMysql.secondInterval");
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setStateBackend((StateBackend) new FsStateBackend(checkpointDirectory, true)); CheckpointConfig checkpointConfig = env.getCheckpointConfig(); checkpointConfig.setCheckpointInterval(checkpointSecondInterval * 1000); checkpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE); checkpointConfig.enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
Properties kafkaProperties = new Properties(); kafkaProperties.put("bootstrap.servers",fromKafkaBootstrapServers); kafkaProperties.put("group.id",fromKafkaGroupID);
FlinkKafkaConsumer010<String> kafkaConsumer = new FlinkKafkaConsumer010<>(fromKafkaTopic, new SimpleStringSchema(), kafkaProperties); kafkaConsumer.setStartFromLatest(); DataStream<String> kafkaSource = env.addSource(kafkaConsumer).name("KafkaSource").uid("source-id-kafka-source");
SingleOutputStreamOperator<Tuple4<String, String, String, Integer>> eventStream = kafkaSource.process(new ProcessFunction<String, Tuple4<String, String, String, Integer>>() { @Override public void processElement(String value, Context ctx, Collector<Tuple4<String, String, String, Integer>> out){ try { JSONObject obj = JSON.parseObject(value); String userID = obj.getString("userID"); String eventTime = obj.getString("eventTime"); String eventType = obj.getString("eventType"); int productID = obj.getIntValue("productID"); out.collect(new Tuple4<>(userID, eventTime, eventType, productID)); }catch (Exception ex){ log.warn("异常数据:{}",value,ex); } } });
DataStreamSource<HashMap<String, Tuple2<String, Integer>>> configStream = env.addSource(new MysqlSource(fromMysqlHost, fromMysqlPort, fromMysqlDB, fromMysqlUser, fromMysqlPasswd, fromMysqlSecondInterval));
MapStateDescriptor<Void, Map<String, Tuple2<String,Integer>>> configDescriptor = new MapStateDescriptor<>("config", Types.VOID, Types.MAP(Types.STRING, Types.TUPLE(Types.STRING, Types.INT)));
BroadcastStream<HashMap<String, Tuple2<String, Integer>>> broadcastConfigStream = configStream.broadcast(configDescriptor);
BroadcastConnectedStream<Tuple4<String, String, String, Integer>, HashMap<String, Tuple2<String, Integer>>> connectedStream = eventStream.connect(broadcastConfigStream);
SingleOutputStreamOperator<Tuple6<String, String, String, Integer, String, Integer>> resultStream = connectedStream.process(new CustomBroadcastProcessFunction());
resultStream.print();
env.execute();
}
static class CustomBroadcastProcessFunction extends BroadcastProcessFunction<Tuple4<String, String, String, Integer>, HashMap<String, Tuple2<String, Integer>>, Tuple6<String, String, String, Integer, String, Integer>>{
MapStateDescriptor<Void, Map<String, Tuple2<String,Integer>>> configDescriptor = new MapStateDescriptor<>("config", Types.VOID, Types.MAP(Types.STRING, Types.TUPLE(Types.STRING, Types.INT)));
@Override public void processElement(Tuple4<String, String, String, Integer> value, ReadOnlyContext ctx, Collector<Tuple6<String, String, String, Integer, String, Integer>> out) throws Exception {
String userID = value.f0;
ReadOnlyBroadcastState<Void, Map<String, Tuple2<String, Integer>>> broadcastState = ctx.getBroadcastState(configDescriptor); Map<String, Tuple2<String, Integer>> broadcastStateUserInfo = broadcastState.get(null);
Tuple2<String, Integer> userInfo = broadcastStateUserInfo.get(userID); if(userInfo!=null){ out.collect(new Tuple6<>(value.f0,value.f1,value.f2,value.f3,userInfo.f0,userInfo.f1)); }
}
@Override public void processBroadcastElement(HashMap<String, Tuple2<String, Integer>> value, Context ctx, Collector<Tuple6<String, String, String, Integer, String, Integer>> out) throws Exception {
BroadcastState<Void, Map<String, Tuple2<String, Integer>>> broadcastState = ctx.getBroadcastState(configDescriptor);
broadcastState.clear();
broadcastState.put(null,value);
} }
static class MysqlSource extends RichSourceFunction<HashMap<String, Tuple2<String, Integer>>> {
private String host; private Integer port; private String db; private String user; private String passwd; private Integer secondInterval;
private volatile boolean isRunning = true;
private Connection connection; private PreparedStatement preparedStatement;
MysqlSource(String host, Integer port, String db, String user, String passwd,Integer secondInterval) { this.host = host; this.port = port; this.db = db; this.user = user; this.passwd = passwd; this.secondInterval = secondInterval; }
@Override public void open(Configuration parameters) throws Exception { super.open(parameters); Class.forName("com.mysql.jdbc.Driver"); connection= DriverManager.getConnection("jdbc:mysql://"+host+":"+port+"/"+db+"?useUnicode=true&characterEncoding=UTF-8", user, passwd); String sql="select userID,userName,userAge from user_info"; preparedStatement=connection.prepareStatement(sql); }
@Override public void close() throws Exception { super.close();
if(connection!=null){ connection.close(); }
if(preparedStatement !=null){ preparedStatement.close(); } }
@Override public void run(SourceContext<HashMap<String, Tuple2<String, Integer>>> ctx) { try { while (isRunning){ HashMap<String, Tuple2<String, Integer>> output = new HashMap<>(); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()){ String userID = resultSet.getString("userID"); String userName = resultSet.getString("userName"); int userAge = resultSet.getInt("userAge"); output.put(userID,new Tuple2<>(userName,userAge)); } ctx.collect(output); Thread.sleep(1000*secondInterval); } }catch (Exception ex){ log.error("从Mysql获取配置异常...",ex); }
}
@Override public void cancel() { isRunning = false; } } }
|