1. Start Zookeeper2 first. Start Kafka3. Core code
- Producer produces the Java code of the message, generating the word to be counted
Packagestreaming;Importjava.util.Properties; ImportKafka.javaapi.producer.Producer;ImportKafka.producer.KeyedMessage;ImportKafka.producer.ProducerConfig; Public classMyproducer { Public Static voidMain (string[] args) {Properties props=NewProperties (); Props.setproperty ("Metadata.broker.list", "localhost:9092"); Props.setproperty ("Serializer.class", "Kafka.serializer.StringEncoder"); Props.put ("Request.required.acks", "1"); Producerconfig Config=Newproducerconfig (props); //Create the Production objectproducer<string, string> Producer =NewProducer<string, string>(config); //Generating Messageskeyedmessage<string, string> data1 =NewKeyedmessage<string, string> ("Top1", "Test Kafka"); Keyedmessage<string, string> data2 =NewKeyedmessage<string, string> ("Top2", "Hello World"); Try { intI =1; while(I < 100){ //Send Messageproducer.send (DATA1); Producer.send (DATA2); I++; Thread.Sleep (1000); } } Catch(Exception e) {e.printstacktrace (); } producer.close (); } }
- Receive data from a given topic in sparkstreaming and count the words
Packagestreaming;ImportJava.util.HashMap;ImportJava.util.Map;ImportJava.util.regex.Pattern;Importorg.apache.spark.*;Importorg.apache.spark.api.java.function.*;Importorg.apache.spark.streaming.*;ImportOrg.apache.spark.streaming.api.java.JavaDStream;ImportOrg.apache.spark.streaming.api.java.JavaPairDStream;ImportOrg.apache.spark.streaming.api.java.JavaPairReceiverInputDStream;ImportOrg.apache.spark.streaming.api.java.JavaStreamingContext;Importorg.apache.spark.streaming.kafka.KafkaUtils;ImportScala. Tuple2;Importcom.google.common.collect.Lists; Public classKafkastreamingwordcount { Public Static voidMain (string[] args) {//set the match pattern, separated by spaces FinalPattern SPACE = Pattern.compile (""); //address and port to receive dataString zkquorum = "localhost:2181"; //the group where the topic is locatedString Group = "1"; //topic name separated by ","String topics = "TOP1,TOP2"; //number of shards per topic intNumthreads = 2; sparkconf sparkconf=NewSparkconf (). Setappname ("Kafkawordcount"). Setmaster ("local[2]"); Javastreamingcontext JSSC=NewJavastreamingcontext (sparkconf,NewDuration (10000));//jssc.checkpoint ("Checkpoint");//set up checkpoints//the mapping between the topic and the Shardmap<string, integer> topicmap =NewHashmap<>(); String[] Topicsarr= Topics.split (","); intn =topicsarr.length; for(inti=0;i<n;i++) {topicmap.put (topicsarr[i], numthreads); } //get data from Kafka into RddJavapairreceiverinputdstream<string, string> lines =Kafkautils.createstream (JSSC, Zkquorum, Group, TOPICMAP); //filter the required data from the topicjavadstream<string> words = Lines.flatmap (NewFlatmapfunction<tuple2<string, String>, string>() {@Override PublicIterable<string> Call (tuple2<string, string>arg0)throwsException {returnlists.newarraylist (Space.split (arg0._2)); } }); //to count the words in themjavapairdstream<string, integer> wordcounts =Words.maptopair (NewPairfunction<string, String, integer>() {@Override PublicTuple2<string, integer>Call (String s) {return NewTuple2<string, Integer> (S, 1); }}). Reducebykey (NewFunction2<integer, Integer, integer>() {@Override Publicinteger Call (integer i1, integer i2) {returnI1 +I2; } }); //Print ResultsWordcounts.print (); Jssc.start (); Jssc.awaittermination (); }}
Spark streaming receive Kafka data Java code wordcount example