Sanjana Agarwal | cb4a3db | 2016-07-14 11:42:48 -0700 | [diff] [blame^] | 1 | /** |
| 2 | * Copyright 2016-present Open Networking Laboratory |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package org.onosproject.kafkaintegration.kafka; |
| 18 | |
| 19 | import org.apache.kafka.clients.producer.KafkaProducer; |
| 20 | import org.apache.kafka.clients.producer.ProducerRecord; |
| 21 | import org.apache.kafka.clients.producer.RecordMetadata; |
| 22 | import org.slf4j.Logger; |
| 23 | import org.slf4j.LoggerFactory; |
| 24 | |
| 25 | import java.util.Properties; |
| 26 | import java.util.concurrent.Future; |
| 27 | |
| 28 | /** |
| 29 | * Implementation of Kafka Producer. |
| 30 | */ |
| 31 | public class Producer { |
| 32 | private KafkaProducer<String, byte[]> kafkaProducer = null; |
| 33 | |
| 34 | private final Logger log = LoggerFactory.getLogger(getClass()); |
| 35 | |
| 36 | Producer(String bootstrapServers, int retries, int maxInFlightRequestsPerConnection, |
| 37 | int requestRequiredAcks, String keySerializer, String valueSerializer) { |
| 38 | |
| 39 | Properties prop = new Properties(); |
| 40 | prop.put("bootstrap.servers", bootstrapServers); |
| 41 | prop.put("retries", retries); |
| 42 | prop.put("max.in.flight.requests.per.connection", maxInFlightRequestsPerConnection); |
| 43 | prop.put("request.required.acks", requestRequiredAcks); |
| 44 | prop.put("key.serializer", keySerializer); |
| 45 | prop.put("value.serializer", valueSerializer); |
| 46 | |
| 47 | kafkaProducer = new KafkaProducer<>(prop); |
| 48 | } |
| 49 | |
| 50 | public void start() { |
| 51 | log.info("Started"); |
| 52 | } |
| 53 | |
| 54 | public void stop() { |
| 55 | if (kafkaProducer != null) { |
| 56 | kafkaProducer.close(); |
| 57 | kafkaProducer = null; |
| 58 | } |
| 59 | |
| 60 | log.info("Stopped"); |
| 61 | } |
| 62 | |
| 63 | public Future<RecordMetadata> send(ProducerRecord<String, byte[]> record) { |
| 64 | return kafkaProducer.send(record); |
| 65 | } |
| 66 | } |