MessageReceiver.java
2.46 KB
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
package cn.com.glsx.entmicro.kafka;
import kafka.consumer.Consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.message.MessageAndMetadata;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* kafka消费
*
* @author zhouhaibao
* @date
*/
@Slf4j
public abstract class MessageReceiver {
protected ConsumerConfig consumerConfig;
protected String topic;
protected Integer nThreads;
protected kafka.javaapi.consumer.ConsumerConnector connector;
protected Map<String, Integer> topicCountMap = new HashMap<>();
public abstract void processMessage(String topic,byte[] message);
protected void init() {
connector = Consumer.createJavaConsumerConnector(consumerConfig);
int threadCnt = 1;
if (null != nThreads && nThreads > 0) {
threadCnt = nThreads;
}
String[] topics = topic.split(",");
for (int i = 0; i < topics.length; i++) {
topicCountMap.put(topics[i], threadCnt);
}
Map<String, List<KafkaStream<byte[], byte[]>>> streams = connector.createMessageStreams(topicCountMap);
List<KafkaStream<byte[], byte[]>> list = new ArrayList<>();
for (String ss : topics) {
list.addAll(streams.get(ss));
}
final ExecutorService executor = Executors.newFixedThreadPool(threadCnt * topics.length);
for (final KafkaStream<byte[], byte[]> kafkaStream : list) {
executor.submit(() -> {
ConsumerIterator<byte[], byte[]> it = kafkaStream.iterator();
while (it.hasNext()) {
MessageAndMetadata<byte[], byte[]> item = it.next();
byte[] message = item.message();
try {
processMessage(item.topic(),message);
} catch (Exception e) {
log.error(e.getMessage());
}
}
});
}
Runtime.getRuntime().addShutdownHook(new Thread(executor::shutdown));
}
public void destroy() {
if (null != connector)
connector.shutdown();
}
public ConsumerConfig getConsumerConfig() {
return consumerConfig;
}
public void setConsumerConfig(ConsumerConfig consumerConfig) {
this.consumerConfig = consumerConfig;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic.trim().replaceAll(" ", "");
}
public Integer getnThreads() {
return nThreads;
}
public void setnThreads(Integer nThreads) {
this.nThreads = nThreads;
}
}