关闭

Kafka Java Producer实例

标签: KafkaJava
282人阅读 评论(0) 收藏 举报
分类:

Kafka Java Producer实例

下面是我测试的使用Java API 来发送Kafka消息的实例

环境:

maven 依赖

  1. <dependency>
  2. <groupId>org.apache.kafka</groupId>
  3. <artifactId>kafka_2.11</artifactId>
  4. <version>0.8.2.2</version>
  5. </dependency>

代码:
package com.earclouds.kafka;

import java.util.Date;
import java.util.Properties;
import java.util.Random;

import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;

public class MyProducer {

	
	 public static void main(String[] args) {
	        long events = 10L;
	        Random rnd = new Random();
	 
	        Properties props = new Properties();
	        props.put("metadata.broker.list", "master:9092");//这里原来写的ip地址,结果连接不上,使用主机名连上了
	        props.put("serializer.class", "kafka.serializer.StringEncoder");
	        props.put("request.required.acks", "1");
	 
	        ProducerConfig config = new ProducerConfig(props);
	 
	        Producer<String, String> producer = new Producer<String, String>(config);
	 
	        for (long nEvents = 0; nEvents < events; nEvents++) { 
	               long runtime = new Date().getTime();  
	               String ip = "192.168.2." + rnd.nextInt(255); 
	               String msg = runtime + ",www.example.com," + ip;
	               System.out.println(msg);
	               KeyedMessage<String, String> data = new KeyedMessage<String, String>("page_visit", ip, msg);
	               producer.send(data);
	               System.out.println(data);
	        }
	        producer.close();
	    }
}







0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:543787次
    • 积分:5100
    • 等级:
    • 排名:第5457名
    • 原创:141篇
    • 转载:103篇
    • 译文:0篇
    • 评论:85条
    最新评论