-
Notifications
You must be signed in to change notification settings - Fork 121
/
CoreApp.java
233 lines (191 loc) · 8.08 KB
/
CoreApp.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
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
package io.confluent.parallelconsumer.examples.core;
/*-
* Copyright (C) 2020-2024 Confluent, Inc.
*/
import io.confluent.parallelconsumer.ParallelConsumerOptions;
import io.confluent.parallelconsumer.ParallelStreamProcessor;
import io.confluent.parallelconsumer.RecordContext;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.concurrent.CircuitBreakingException;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import static io.confluent.csid.utils.StringUtils.msg;
import static io.confluent.parallelconsumer.ParallelConsumerOptions.ProcessingOrder.KEY;
import static pl.tlinkowski.unij.api.UniLists.of;
/**
* Basic core examples
*/
@Slf4j
public class CoreApp {
String inputTopic = "input-topic-" + RandomUtils.nextInt();
String outputTopic = "output-topic-" + RandomUtils.nextInt();
Consumer<String, String> getKafkaConsumer() {
return new KafkaConsumer<>(new Properties());
}
Producer<String, String> getKafkaProducer() {
return new KafkaProducer<>(new Properties());
}
ParallelStreamProcessor<String, String> parallelConsumer;
@SuppressWarnings("UnqualifiedFieldAccess")
void run() {
this.parallelConsumer = setupParallelConsumer();
postSetup();
// tag::example[]
parallelConsumer.poll(record ->
log.info("Concurrently processing a record: {}", record)
);
// end::example[]
}
protected void postSetup() {
// ignore
}
@SuppressWarnings({"FeatureEnvy", "MagicNumber"})
ParallelStreamProcessor<String, String> setupParallelConsumer() {
// tag::exampleSetup[]
Consumer<String, String> kafkaConsumer = getKafkaConsumer(); // <1>
Producer<String, String> kafkaProducer = getKafkaProducer();
var options = ParallelConsumerOptions.<String, String>builder()
.ordering(KEY) // <2>
.maxConcurrency(1000) // <3>
.consumer(kafkaConsumer)
.producer(kafkaProducer)
.build();
ParallelStreamProcessor<String, String> eosStreamProcessor =
ParallelStreamProcessor.createEosStreamProcessor(options);
eosStreamProcessor.subscribe(of(inputTopic)); // <4>
return eosStreamProcessor;
// end::exampleSetup[]
}
void close() {
this.parallelConsumer.close();
}
void runPollAndProduce() {
this.parallelConsumer = setupParallelConsumer();
postSetup();
// tag::exampleProduce[]
parallelConsumer.pollAndProduce(context -> {
var consumerRecord = context.getSingleRecord().getConsumerRecord();
var result = processBrokerRecord(consumerRecord);
return new ProducerRecord<>(outputTopic, consumerRecord.key(), result.payload);
}, consumeProduceResult -> {
log.debug("Message {} saved to broker at offset {}",
consumeProduceResult.getOut(),
consumeProduceResult.getMeta().offset());
}
);
// end::exampleProduce[]
}
private Result processBrokerRecord(ConsumerRecord<String, String> consumerRecord) {
return new Result("Some payload from " + consumerRecord.value());
}
@Value
static class Result {
String payload;
}
void customRetryDelay() {
// tag::customRetryDelay[]
final double multiplier = 0.5;
final int baseDelaySecond = 1;
ParallelConsumerOptions.<String, String>builder()
.retryDelayProvider(recordContext -> {
int numberOfFailedAttempts = recordContext.getNumberOfFailedAttempts();
long delayMillis = (long) (baseDelaySecond * Math.pow(multiplier, numberOfFailedAttempts) * 1000);
return Duration.ofMillis(delayMillis);
});
// end::customRetryDelay[]
}
void maxRetries() {
ParallelStreamProcessor<String, String> pc = ParallelStreamProcessor.createEosStreamProcessor(null);
// tag::maxRetries[]
final int maxRetries = 10;
final Map<ConsumerRecord<String, String>, Long> retriesCount = new ConcurrentHashMap<>();
pc.poll(context -> {
var consumerRecord = context.getSingleRecord().getConsumerRecord();
Long retryCount = retriesCount.compute(consumerRecord, (key, oldValue) -> oldValue == null ? 0L : oldValue + 1);
if (retryCount < maxRetries) {
processRecord(consumerRecord);
// no exception, so completed - remove from map
retriesCount.remove(consumerRecord);
} else {
log.warn("Retry count {} exceeded max of {} for record {}", retryCount, maxRetries, consumerRecord);
// giving up, remove from map
retriesCount.remove(consumerRecord);
}
});
// end::maxRetries[]
}
private void processRecord(final ConsumerRecord<String, String> record) {
// no-op
}
void circuitBreaker() {
ParallelStreamProcessor<String, String> pc = ParallelStreamProcessor.createEosStreamProcessor(null);
// tag::circuitBreaker[]
final Map<String, Boolean> upMap = new ConcurrentHashMap<>();
pc.poll(context -> {
var consumerRecord = context.getSingleRecord().getConsumerRecord();
String serverId = extractServerId(consumerRecord);
boolean up = upMap.computeIfAbsent(serverId, ignore -> true);
if (!up) {
up = updateStatusOfSever(serverId);
}
if (up) {
try {
processRecord(consumerRecord);
} catch (CircuitBreakingException e) {
log.warn("Server {} is circuitBroken, will retry message when server is up. Record: {}", serverId, consumerRecord);
upMap.put(serverId, false);
}
// no exception, so set server status UP
upMap.put(serverId, true);
} else {
throw new RuntimeException(msg("Server {} currently down, will retry record latter {}", up, consumerRecord));
}
});
// end::circuitBreaker[]
}
private boolean updateStatusOfSever(final String serverId) {
return false;
}
private String extractServerId(final ConsumerRecord<String, String> consumerRecord) {
// no-op
return null;
}
void batching() {
// tag::batching[]
ParallelStreamProcessor.createEosStreamProcessor(ParallelConsumerOptions.<String, String>builder()
.consumer(getKafkaConsumer())
.producer(getKafkaProducer())
.maxConcurrency(100)
.batchSize(5) // <1>
.build());
parallelConsumer.poll(context -> {
// convert the batch into the payload for our processing
List<String> payload = context.stream()
.map(this::preparePayload)
.collect(Collectors.toList());
// process the entire batch payload at once
processBatchPayload(payload);
});
// end::batching[]
}
private void processBatchPayload(List<String> batchPayload) {
// example
}
private String preparePayload(RecordContext<String, String> rc) {
ConsumerRecord<String, String> consumerRecords = rc.getConsumerRecord();
int failureCount = rc.getNumberOfFailedAttempts();
return msg("{}, {}", consumerRecords, failureCount);
}
}