码迷,mamicode.com
首页 > 其他好文 > 详细

kafka安装以及入门demo

时间:2015-09-11 16:02:36      阅读:500      评论:0      收藏:0      [点我收藏+]

标签:

jdk:1.6.0_25 64位

kafka:2.9.2-0.8.2.1

kafka 官方下载地址 http://apache.fayea.com/kafka/0.8.2.1/kafka_2.9.2-0.8.2.1.tgz

 

tar -zxvf kafka_2.9.2-0.8.2.1.tgz -C /usr/local/ && mv kafka_2.9.2-0.8.2.1 kafka
cd /usr/local/kafka
vi config/zookeeper.properties

dataDir=/usr/local/kafka/zookeeper

vi config/server.properties
broker.id=0
port=9092
hostname=192.168.194.110
log.dirs=/usr/local/kafka/kafka-logs
zookeeper.connect=192.168.194.110:2181

 启动zookeeper

bin/zookeeper-server-start.sh config/zookeeper.properties  

启动kafka broker

bin/kafka-server-start.sh config/server.properties &

查看启动状态

jps
14867 QuorumPeerMain ###存在代表zookeeper服务启动正常

14919 Kafka ###代表kafka broker启动成功 

关闭防火墙 

service iptables stop

单机版kafka producer consumer 消息发送和接收测试

bin/kafka-console-producer.sh --broker-list 192.168.194.110:9092 --topic test ###启动producer 

bin/kafka-console-consumer.sh --zookeeper 192.168.194.110:2181 --topic test --from-beginning 

然后在producer端 输入需要发送的msg内容 回车 看consumer端是否接收到消息

[2015-09-11 13:58:00,470] ERROR Error in handling batch of 1 events (kafka.producer.async.ProducerSendThread)
kafka.common.FailedToSendMessageException: Failed to send messages after 3 tries.
    at kafka.producer.async.DefaultEventHandler.handle(DefaultEventHandler.scala:90)
    at kafka.producer.async.ProducerSendThread.tryToHandle(ProducerSendThread.scala:105)
    at kafka.producer.async.ProducerSendThread$$anonfun$processEvents$3.apply(ProducerSendThread.scala:88)
    at kafka.producer.async.ProducerSendThread$$anonfun$processEvents$3.apply(ProducerSendThread.scala:68)
    at scala.collection.immutable.Stream.foreach(Stream.scala:526)
    at kafka.producer.async.ProducerSendThread.processEvents(ProducerSendThread.scala:67)at kafka.producer.async.ProducerSendThread.run(ProducerSendThread.scala:45)

producer端出现此异常 请将producer监听的broker 使用ip地址 不要用localhost  

到此 单机版kafka已搭建并测试成功了

使用java来调用kafka的producer发消息和consumer来发消息

maven添加依赖
1 <dependency>  
2         <groupId>org.apache.kafka</groupId>  
3         <artifactId>kafka_2.10</artifactId>  
4         <version>0.8.2.0</version>  
5     </dependency> 

 kafka消息生产者KafkaProducer

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 KafkaProducer extends Thread {
      
      
      
    public static void main(String[] args) {  
        Properties props = new Properties();
        props.put("metadata.broker.list", "192.168.194.110:9092");
        props.put("serializer.class", "kafka.serializer.StringEncoder");
        props.put("key.serializer.class", "kafka.serializer.StringEncoder");
        props.put("request.required.acks", "1");
        
        //配置key的序列化类
        ProducerConfig config = new ProducerConfig(props);
        Producer<String, String> producer = new Producer<String, String>(config);
        Random rnd = new Random();
         
        long runtime = new Date().getTime();
         
        String ip = "192.168.2." + rnd.nextInt(255);
         
        String msg = runtime + ",www.example.com," + ip;
        KeyedMessage<String, String> data = new KeyedMessage<String, String>("test", "test-key",msg);
        producer.send(data);
    }  
       
}  

kafka消息消费者 KafkaConsumer 

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 KafkaConsumer{
      
      
    private static ConsumerConnector consumer = null;
    public static void main(String[] args) {  
         Properties props = new Properties();
         //zookeeper 配置
         props.put("zookeeper.connect", "192.168.194.110:2181");

         //group 代表一个消费组
         props.put("group.id", "jd-group");

         //zk连接超时
         props.put("zookeeper.session.timeout.ms", "4000");
         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);
         
         Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
         topicCountMap.put("test", 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("test").get(0);
         ConsumerIterator<String, String> it = stream.iterator();
         while (it.hasNext())
             System.out.println(it.next().message());
    }  
       
}  

 分别启动producer 和consumer 即可进行简单的消息发送和接收

 结果:

log4j:WARN No appenders could be found for logger (kafka.utils.VerifiableProperties).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
1441952197141,www.example.com,192.168.2.86

 

kafka安装以及入门demo

标签:

原文地址:http://www.cnblogs.com/hxy520/p/4800787.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!