1. 生产者

import java.util.Properties; 

import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig; public class MyProducer { public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("metadata.broker.list","localhost:9092");
props.setProperty("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);
//生成消息
KeyedMessage<String, String> data = new KeyedMessage<String, String>("mykafka","test-kafka");
try {
int i =1;
while(i < 100){
//发送消息
producer.send(data);
}
} catch (Exception e) {
e.printStackTrace();
}
producer.close();
}
}

2. 消费者

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; public class MyConsumer extends Thread{
//消费者连接
private final ConsumerConnector consumer;
//要消费的话题
private final String topic; public MyConsumer(String topic) {
consumer =kafka.consumer.Consumer
.createJavaConsumerConnector(createConsumerConfig());
this.topic =topic;
} //配置相关信息
private static ConsumerConfig createConsumerConfig() {
Properties props = new Properties();
// props.put("zookeeper.connect","localhost:2181,10.XX.XX.XX:2181,10.XX.XX.XX:2181");
//配置要连接的zookeeper地址与端口
//The ‘zookeeper.connect’ string identifies where to find once instance of Zookeeper in your cluster.
//Kafka uses ZooKeeper to store offsets of messages consumed for a specific topic and partition by this Consumer Group
props.put("zookeeper.connect","localhost:2181"); //配置zookeeper的组id (The ‘group.id’ string defines the Consumer Group this process is consuming on behalf of.)
props.put("group.id", "0"); //配置zookeeper连接超时间隔
//The ‘zookeeper.session.timeout.ms’ is how many milliseconds Kafka will wait for
//ZooKeeper to respond to a request (read or write) before giving up and continuing to consume messages.
props.put("zookeeper.session.timeout.ms","10000"); //The ‘zookeeper.sync.time.ms’ is the number of milliseconds a ZooKeeper ‘follower’ can be behind the master before an error occurs.
props.put("zookeeper.sync.time.ms", "200"); //The ‘auto.commit.interval.ms’ setting is how often updates to the consumed offsets are written to ZooKeeper.
//Note that since the commit frequency is time based instead of # of messages consumed, if an error occurs between updates to ZooKeeper on restart you will get replayed messages.
props.put("auto.commit.interval.ms", "1000");
return new ConsumerConfig(props);
} public void run(){ Map<String,Integer> topickMap = new HashMap<String, Integer>();
topickMap.put(topic, 1);
Map<String, List<KafkaStream<byte[],byte[]>>> streamMap =consumer.createMessageStreams(topickMap); KafkaStream<byte[],byte[]>stream = streamMap.get(topic).get(0);
ConsumerIterator<byte[],byte[]> it =stream.iterator();
System.out.println("*********Results********");
while(true){
if(it.hasNext()){
//打印得到的消息
System.err.println(Thread.currentThread()+" get data:" +new String(it.next().message()));
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} public static void main(String[] args) {
MyConsumer consumerThread = new MyConsumer("mykafka");
consumerThread.start();
}
}

3. 消费者的线程执行器实现

  首先建立一个处理消息的类Consumer

import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
public class Consumer implements Runnable { private KafkaStream stream;
private int threadNumber; public Consumer(KafkaStream a_stream, int a_threadNumber) {
threadNumber = a_threadNumber;
stream = a_stream;
} public void run() {
ConsumerIterator<byte[], byte[]> it = stream.iterator();
while (it.hasNext())
System.out.println("Thread " + threadNumber + ": " + new String(it.next().message()));
System.out.println("Shutting down Thread: " + threadNumber);
}
}

  其次实现多线程的调用

import kafka.consumer.ConsumerConfig;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector; import java.util.concurrent.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class ConsumerGroup {
private final ConsumerConnector consumer;
private final String topic;
private ExecutorService executor; public ConsumerGroup(String a_zookeeper, String a_groupId, String a_topic) {
consumer = kafka.consumer.Consumer.createJavaConsumerConnector(
createConsumerConfig(a_zookeeper, a_groupId));
this.topic = a_topic;
} public void shutdown() {
if (consumer != null) consumer.shutdown();
if (executor != null) executor.shutdown();
try {
if (!executor.awaitTermination(5000, TimeUnit.MILLISECONDS)) {
System.out.println("Timed out waiting for consumer threads to shut down, exiting uncleanly");
}
} catch (InterruptedException e) {
System.out.println("Interrupted during shutdown, exiting uncleanly");
}
} public void run(int a_numThreads) {
Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
topicCountMap.put(topic, new Integer(a_numThreads));
Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumer.createMessageStreams(topicCountMap);
List<KafkaStream<byte[], byte[]>> streams = consumerMap.get(topic); // now launch all the threads
//
executor = Executors.newFixedThreadPool(a_numThreads); // now create an object to consume the messages
//
int threadNumber = 0;
for (final KafkaStream stream : streams) {
executor.submit(new Consumer(stream, threadNumber));
threadNumber++;
}
} private static ConsumerConfig createConsumerConfig(String a_zookeeper, String a_groupId) {
Properties props = new Properties();
props.put("zookeeper.connect", a_zookeeper);
props.put("group.id", a_groupId);
props.put("zookeeper.session.timeout.ms", "400");
props.put("zookeeper.sync.time.ms", "200");
props.put("auto.commit.interval.ms", "1000"); return new ConsumerConfig(props);
} public static void main(String[] args) {
String zooKeeper = "localhost:2181";
String groupId = "0";
String topic = "mykafka";
int threads = 2; //启动的线程数 ConsumerGroup group = new ConsumerGroup(zooKeeper, groupId, topic);
group.run(threads); try {
Thread.sleep(10000);
} catch (InterruptedException ie) { }
group.shutdown();
}
}

kafka生产者、消费者java示例的更多相关文章

  1. Python 使用python-kafka类库开发kafka生产者&消费者&客户端

    使用python-kafka类库开发kafka生产者&消费者&客户端   By: 授客 QQ:1033553122       1.测试环境 python 3.4 zookeeper- ...

  2. kafka消息中间件及java示例

    kafka是一个消息中间件,用于各个系统之间传递消息,并且消息可持久化! 可以认为是队列模型,也可以看作是生产者消费着模型: 简单的生产者消费者客户端代码如下: package com.pt.util ...

  3. kafka 生产者消费者 api接口

    生产者 import java.util.Properties; import kafka.javaapi.producer.Producer; import kafka.producer.Keyed ...

  4. 经典线程同步问题(生产者&消费者)--Java实现

    生产者-消费者(producer-consumer)问题是一个著名的线程同步问题.它描述的是:有一群生产者线程在生产产品,并将这些产品提供给消费者线程去消费. 为使生产者与消费者之间能够并发执行,在两 ...

  5. Linux组件封装(五)一个生产者消费者问题示例

    生产者消费者问题是计算机中一类重要的模型,主要描述的是:生产者往缓冲区中放入产品.消费者取走产品.生产者和消费者指的可以是线程也可以是进程. 生产者消费者问题的难点在于: 为了缓冲区数据的安全性,一次 ...

  6. kafka集群搭建和使用Java写kafka生产者消费者

    1 kafka集群搭建 1.zookeeper集群  搭建在110, 111,112 2.kafka使用3个节点110, 111,112 修改配置文件config/server.properties ...

  7. java kafka 生产者消费者demo

    一.修改kafka   server.porperties的ip是你本机的ip listeners=PLAINTEXT://192.168.111.130:9092 二.生产者的例子 import o ...

  8. 生产者消费者-Java代码实现

    import java.util.LinkedList; class Storage{ private static final int MAX = 100; LinkedList<Object ...

  9. 生产者消费者 java.util.concurrent.lock包

    package com.mozq.thread.producer2; import java.util.concurrent.locks.Condition; import java.util.con ...

随机推荐

  1. netty 基础知识

    http://my.oschina.net/bieber/blog/406799 线程模型 http://hongweiyi.com/2014/01/netty-4-x-thread-model/ h ...

  2. 使用亚马逊云服务器EC2做深度学习(三)配置TensorFlow

    这是<使用亚马逊云服务器EC2做深度学习>系列的第三篇文章. (一)申请竞价实例  (二)配置Jupyter Notebook服务器  (三)配置TensorFlow  (四)配置好的系统 ...

  3. 救济金发放(UVa133)

    题目具体描述见:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_prob ...

  4. Python网络管理模块Paramiko-代码实例

    import paramiko import time import sys ip = "10.1.1.1" username = "Admin" passwo ...

  5. zstuoj 4245 KI的斐波那契

    KI的斐波那契 Time Limit: 1 Sec  Memory Limit: 128 MB Submit: 550  Solved: 208 Description KI十分喜欢美丽而优雅的斐波那 ...

  6. 使用matplotlib绘图(二)之柱状图

    # 使用matplotlib绘制柱状图 import numpy as np import matplotlib.pyplot as plt # 设置全局字体,以支持中文 plt.rcParams[' ...

  7. FastReport.Net使用:[11]公共对象属性介绍

    公共对象属性介绍 1.Left(左),Top(上),Height(高度),Width(宽度) Left和Top,用来控制对象的位置:Height和Width用来控制对象的大小. 2.Anchor(基准 ...

  8. CODEVS1358【DFS/状压DP】

    题目链接[http://codevs.cn/problem/1358/] 题意:这个游戏在一个有10*10个格子的棋盘上进行,初始时棋子位于左上角,终点为右下角,棋盘上每个格子内有一个0到9的数字,每 ...

  9. dp洋洋散散的知识+code

    /*在数轴上有0-N的位置 从0出发每次可以向右走 2 23 233步*/ // 1 总共的方案数 f[i]=f[i-]+f[i-]+f[i-]; f[]=; ;a<=n;a++) { ) f[ ...

  10. ACM -- 算法小结(三)反转句子顺序与反转单词组成顺序

    hdoj 1321 反转句子字母顺序 ac 2011/10/05 #include <iostream> #include <string> #include <algo ...