-
Notifications
You must be signed in to change notification settings - Fork 0
/
Consumer.java
66 lines (60 loc) · 2.57 KB
/
Consumer.java
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
// Reza Marzban
// Kafka
//Consumer
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import java.util.ArrayList;
import java.util.Collections;
//Our Main Consumer gets the messages with Topic kafka_Max, and then calculate the max of all values and print it out.
public class Consumer{
public static void main(String[] args) {
//creating default properties
Properties properties = new Properties();
properties.put("bootstrap.servers", "localhost:9092");
//Group id of this consumer is Reza
properties.put("group.id", "Reza");
properties.put("enable.auto.commit", "true");
properties.put("auto.commit.interval.ms", "1000");
properties.put("session.timeout.ms", "30000");
//both key and value are using IntegerDeserializer
properties.put("key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer");
properties.put("value.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer");
//create a kafka Consumer with our properties
KafkaConsumer<Integer,Integer> Consumer1 = new KafkaConsumer<Integer,Integer>(properties);
//create an array of topics that our consumer will subscribe to.
ArrayList ConsumerTopics = new ArrayList();
//add kafka_Max to our ConsumerTopics
ConsumerTopics.add("kafka_Max");
//subscribe kafkaConsumer to all of topics
Consumer1.subscribe(ConsumerTopics);
ArrayList<Integer> values = new ArrayList();
System.out.println();
System.out.println("______________________________________________________________");
int i=1;
try{
while (true){
if(i>500){break;}
//get 100 record each time
ConsumerRecords<Integer, Integer> records = Consumer1.poll(100);
for (ConsumerRecord<Integer, Integer> record: records){
// add the value of each record to the arraylist
values.add(record.value());
i++;
}
}
}catch (Exception e){
//print the error
System.out.println(e.getMessage());
}finally {
//get the maximum of all received values and print it out.
Integer Maximum=Collections.max(values);
System.out.print("The maximum value is: ");
System.out.println(Maximum);
System.out.println("______________________________________________________________");
//close the consumer
Consumer1.close();
}
}
}