|
| 1 | +package streaming; |
| 2 | + |
| 3 | +import org.apache.kafka.clients.consumer.ConsumerConfig; |
| 4 | +import org.apache.kafka.clients.consumer.ConsumerRecord; |
| 5 | +import org.apache.kafka.common.serialization.StringDeserializer; |
| 6 | +import org.apache.spark.SparkConf; |
| 7 | +import org.apache.spark.streaming.Durations; |
| 8 | +import org.apache.spark.streaming.api.java.JavaInputDStream; |
| 9 | +import org.apache.spark.streaming.api.java.JavaStreamingContext; |
| 10 | +import org.apache.spark.streaming.kafka010.ConsumerStrategies; |
| 11 | +import org.apache.spark.streaming.kafka010.ConsumerStrategy; |
| 12 | +import org.apache.spark.streaming.kafka010.KafkaUtils; |
| 13 | +import org.apache.spark.streaming.kafka010.LocationStrategies; |
| 14 | + |
| 15 | +import java.util.Collections; |
| 16 | +import java.util.HashMap; |
| 17 | +import java.util.Map; |
| 18 | + |
| 19 | +public class ByKafka { |
| 20 | + |
| 21 | + public static void main(String[] args) throws InterruptedException { |
| 22 | + SparkConf sparkConf = new SparkConf() |
| 23 | + .setMaster("local") |
| 24 | + .setAppName("test"); |
| 25 | + JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, Durations.seconds(5)); |
| 26 | + |
| 27 | + // kafka配置 |
| 28 | + Map<String, Object> kafkaParams = new HashMap<>(); |
| 29 | + kafkaParams.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.31.201:9092,192.168.31.202:9092,192.168.31.203:9092"); |
| 30 | + kafkaParams.put(ConsumerConfig.GROUP_ID_CONFIG, "spark"); |
| 31 | + kafkaParams.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); |
| 32 | + kafkaParams.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); |
| 33 | + |
| 34 | + // 数据处理 |
| 35 | + // 数据发送于: middleware/kafka/src/main/java/com/example/kafka/KafkaApplication.java |
| 36 | + ConsumerStrategy<Object, Object> consumerStrategy = ConsumerStrategies.Subscribe(Collections.singleton("random"), kafkaParams); |
| 37 | + JavaInputDStream<ConsumerRecord<Object, Object>> dStream = KafkaUtils.createDirectStream(jssc, LocationStrategies.PreferConsistent(), consumerStrategy); |
| 38 | + dStream |
| 39 | + .map(ConsumerRecord::value) |
| 40 | + .print(); |
| 41 | + |
| 42 | + // 启动 |
| 43 | + jssc.start(); |
| 44 | + jssc.awaitTermination(); |
| 45 | + } |
| 46 | + |
| 47 | +} |
0 commit comments