使用java编写kafka的生产者

来源:互联网 发布:网络水军兼职 编辑:程序博客网 时间:2024/06/06 19:26

一,定义常量

public class Constant{    public static final String TOPIC = "test"; //kafka创建的topic    public static final String CONTENT = "This is a single message"; //要发送的内容    public static final String BROKER_LIST = "xx.xx.xx.xx:xxxx"; //broker的地址和端口    public static final String SERIALIZER_CLASS = "kafka.serializer.StringEncoder"; // 序列化类}

二,定义kafka的Producer

import com.constant.Constant;import kafka.javaapi.producer.Producer;import kafka.producer.KeyedMessage;import kafka.producer.ProducerConfig;import java.util.Properties;public class KafkaProducer {    public void kafkaProducerSentOneJsonMessage(String content){        Properties props = new Properties();        props.put("serializer.class", Constant.SERIALIZER_CLASS);        props.put("metadata.broker.list", Constant.BROKER_LIST);        ProducerConfig config = new ProducerConfig(props);        Producer<String, String> producer = new Producer<String, String>(config);        //Send one message.        KeyedMessage<String, String> message = new KeyedMessage<String, String>(Constant.TOPIC, content);        producer.send(message);//        //Send multiple messages.//        List<KeyedMessage<String,String>> messages =//                new ArrayList<KeyedMessage<String, String>>();//        for (int i = 0; i < 5; i++) {//            messages.add(new KeyedMessage<String, String>//                    (TOPIC, "Multiple message at a time. " + i));//        }//        producer.send(messages);    }}

三,编写单元测试调用producer

import com.kafka.KafkaProducer;import org.testng.annotations.Test;public class KafkaProducerTest {    @Test    public void post1() throws Exception {        KafkaProducer kafkaProducer = new KafkaProducer();        String content = "this is a test message for kafkaProducerTesting";        content = content.replace("\n","").replace(" ","");        System.out.println("content = " + content);        kafkaProducer.kafkaProducerSentOneJsonMessage(content);    }}