KAFKA知识(Producer)

来源:互联网 发布:最新金融网络理财产品 编辑:程序博客网 时间:2024/05/29 04:24

构建KAFKA Producer Brokerlist为kafka集群broker地址 可修改为“10.2.1.123,10.2.1.132”格式

static {        Properties props = new Properties();        // 此处配置的是kafka的端口        props.put("metadata.broker.list",BROKERlIST);        // 配置value的序列化类        props.put("serializer.class", "kafka.serializer.StringEncoder");        // 配置key的序列化类        props.put("key.serializer.class", "kafka.serializer.StringEncoder");        props.put("request.required.acks", "-1");                producer = new Producer<String, String>(new ProducerConfig(props));        }

producer

private static Producer<String, String> producer;

发送消息体 topic为主题  conent为发送内容

   producer.send(new KeyedMessage<String, String>(TOPIC, CONTENT));   


整体源码:

import java.util.Properties;import kafka.javaapi.producer.Producer;import kafka.producer.KeyedMessage;import kafka.producer.ProducerConfig;public class KafkaProducer {        // 生产者    private static Producer<String, String> producer;        static {          Properties props = new Properties();          // 此处配置的是kafka的端口          props.put("metadata.broker.list","10.2.4.13:9092,10.2.4.14:9092,10.2.4.12:9092");          // 配置value的序列化类          props.put("serializer.class", "kafka.serializer.StringEncoder");          // 配置key的序列化类          props.put("key.serializer.class", "kafka.serializer.StringEncoder");          props.put("request.required.acks", "-1");                    producer = new Producer<String, String>(new ProducerConfig(props));    }        public static void main(String[] args) {                for(int i = 0 ;i<100;i++){            producer.send(new KeyedMessage<String, String>("test_rce_yjd", "{json:fjdlasfjldsajfoiewjf}"));            try {                Thread.sleep(3000);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }            }}