Open Kilda Java Documentation
TestKafkaProducer.java
Go to the documentation of this file.
1 /* Copyright 2017 Telstra Open Source
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 package org.openkilda.wfm.topology;
17 
18 import static org.openkilda.messaging.Utils.PAYLOAD;
19 
20 import org.apache.kafka.clients.producer.KafkaProducer;
21 import org.apache.kafka.clients.producer.ProducerRecord;
22 import org.apache.storm.utils.Utils;
23 
24 import java.util.Properties;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.TimeUnit;
27 import java.util.concurrent.TimeoutException;
28 
29 public class TestKafkaProducer {
30  private static final long SEND_TIMEOUT = 1000;
31  private final KafkaProducer<String, String> producer;
32 
33  public TestKafkaProducer(final Properties properties) {
34  this.producer = new KafkaProducer<>(properties);
35  }
36 
37  public void pushMessage(final String topic, final String data) {
38  ProducerRecord<String, String> producerRecord = new ProducerRecord<>(topic, PAYLOAD, data);
39  try {
40  producer.send(producerRecord).get(SEND_TIMEOUT, TimeUnit.MILLISECONDS);
41  producer.flush();
42  System.out.println(String.format("send to %s: %s", topic, data));
43  Utils.sleep(SEND_TIMEOUT);
44  } catch (InterruptedException | TimeoutException | ExecutionException e) {
45  System.out.println(e.getMessage());
46  }
47  }
48 
49  public void pushMessageAsync(final String topic, final String data) {
50  ProducerRecord<String, String> producerRecord = new ProducerRecord<>(topic, PAYLOAD, data);
51  producer.send(producerRecord);
52  }
53 
54  public void flush()
55  {
56  producer.flush();
57  }
58 
59  public void close() {
60  producer.flush();
61  producer.close();
62  }
63 }
static final String PAYLOAD
Definition: Utils.java:57
void pushMessage(final String topic, final String data)
void pushMessageAsync(final String topic, final String data)
TestKafkaProducer(final Properties properties)