kafka代码测试连接
1.发送:
package kafka.test;
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 KafkaProduct {
public static void main(String[] args) {
long events=Long.parseLong("1");
Random random =new Random();
Properties properties =new Properties();
properties.put("metadata.broker.list", "192.168.56.107:9092");
properties.put("serializer.class", "kafka.serializer.StringEncoder");
properties.put("request.required.acks", "1");
ProducerConfig config =new ProducerConfig(properties);
Producer<String,String> producer =new Producer(config);
for(int i=0;i<events;i++){
long runtime=new Date().getTime();
String ip="192.168.56.107";
//String msg=runtime+",helloworld,"+ip;
String msg="网盘哎你的";
KeyedMessage<String, String> keyedMessage=new KeyedMessage<String, String>("page_visits", ip,msg);
System.out.println(events+"---"+runtime);
producer.send(keyedMessage);
}
producer.close();
}
}
2.接收:
package kafka.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.serializer.StringDecoder;
import kafka.utils.VerifiableProperties;
public class KafkaCusmer {
private final ConsumerConnector consumer;
private KafkaCusmer() {
Properties props = new Properties();
// zookeeper 配置
props.put("zookeeper.connect", "192.168.56.107:2181");
// group 代表一个消费组
props.put("group.id", "jd-group");
// zk连接超时
props.put("zookeeper.session.timeout.ms", "40000");
props.put("zookeeper.sync.time.ms", "200");
props.put("auto.commit.interval.ms", "1000");
props.put("auto.offset.reset", "smallest");
// 序列化类
props.put("serializer.class", "kafka.serializer.StringEncoder");
ConsumerConfig config = new ConsumerConfig(props);
consumer = kafka.consumer.Consumer.createJavaConsumerConnector(config);
}
void consume() {
Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
//topicCountMap.put(KafkaProducerDemo.TOPIC, new Integer(1));
topicCountMap.put("page_visits", new Integer(1));
StringDecoder keyDecoder = new StringDecoder(new VerifiableProperties());
StringDecoder valueDecoder = new StringDecoder(new VerifiableProperties());
Map<String, List<KafkaStream<String, String>>> consumerMap = consumer.createMessageStreams(topicCountMap,
keyDecoder, valueDecoder);
KafkaStream<String, String> stream = consumerMap.get("page_visits").get(0);
ConsumerIterator<String, String> it = stream.iterator();
while (it.hasNext())
System.out.println(it.next().message());
}
public static void main(String[] args) {
new KafkaCusmer().consume();
}
}