【发布时间】:2018-04-25 08:03:11
【问题描述】:
我有卡夫卡记录:
ConsumerRecords<String, Events> records = kafkaConsumer.poll(POLL_TIMEOUT);
我想使用并行流而不是多线程来运行以下代码。
records.forEach((record) -> {
Event event = record.value();
HTTPSend.send(event);
});
我尝试了多线程,但我想尝试并行流:
for (ConsumerRecord<String, Event> record : records) {
executor.execute(new Runnable() {
@Override
public void run() {
HTTPSend.send(Event);
}
});
}
实际上,我在 HTTP.send 中遇到了多线程问题(即使是 1 个线程的线程池)。我来了
"Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target"。
这是通过 https 的请求。此错误仅在第一次发出请求时出现。之后,异常消失。噗!
对于我正在使用的多线程:
int threadCOunt=1;
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(threadCOunt, true);
RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();
ExecutorService executor = new ThreadPoolExecutor(threadCOunt, threadCOunt, 0L, TimeUnit.MILLISECONDS, queue, handler);
HTTPSend.send() 是:
long sizeSend = 0;
SSLContext sc = null;
try {
sc = SSLContext.getInstance("TLS");
sc.init(null, TRUST_ALL_CERTS, new SecureRandom());
} catch (NoSuchAlgorithmException | KeyManagementException e) {
LOGGER.error("Failed to create SSL context", e);
}
// Ignore differences between given hostname and certificate hostname
HostnameVerifier hv = (hostname, session) -> true;
// Create the REST client and configure it to connect meta
Client client = ClientBuilder.newBuilder()
.hostnameVerifier(hv)
.sslContext(sc).build();
WebTarget baseTarget = client.target(getURL()).path(HTTP_PATH);
Response jsonResponse = null;
try {
StringBuilder eventsBatchString = new StringBuilder();
eventsBatchString.append(this.getEvent(event));
Entity<String> entity = Entity.entity(eventsBatchString.toString(), MediaType.APPLICATION_JSON_TYPE);
builder = baseTarget.request();
LOGGER.debug("about to send the event {} and URL {}", entity, getURL());
jsonResponse = builder.header(HTTP_ACK_CHANNEL, guid.toString())
.header("Content-type", MediaType.APPLICATION_JSON)
.header("Authorization", String.format("Meta %s", eventsModuleConfig.getSecretKey()))
.post(entity);
【问题讨论】:
标签: java apache-kafka kafka-consumer-api