编程

Producer是一个应用程序。它创建消息并发送它们到Kafka broker中。这些producer在本质上是不同。比方。前端应用程序。后端服务。代理服务。适配器对于潜在的系统,Hadoop对于的Producer。这些不同的Producer可以使用不同的语言实现。比方java、C和Python。

以下的这部图表解释了消息producer的Kafka API.

以下将具体介绍假设编写一个简单的Producer和Consumer应用程序。

发送简单消息给Kafka broker。Producer端编写类ClusterProducer。

public classClusterProducer extends Thread {
private static final Log log =LogFactory.getLog(ClusterProducer.class); public void sendData() {
Random rnd = new Random();
Properties props =PropertiesParser.getProperties(PropertiesSettings.PRODUCER_FILE_NAME);
if (props == null) {
log.error("can't loadspecified file " + PropertiesSettings.PRODUCER_FILE_NAME);
return;
}
//set the producer configurationproperties
ProducerConfig config = newProducerConfig(props);
Producer<String, String> producer= new Producer<String, String>(config); //Send the data
int count = 1;
KeyedMessage<String, String>data;
while (count < 100) {
String sign = "*";
String ip = "192.168.2."+ rnd.nextInt(255);
StringBuffer sb = newStringBuffer();
for (int i = 0; i < count; i++){
sb.append(sign);
}
log.info("set data:" +sb);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
data = new KeyedMessage<String,String>(PropertiesSettings.TOPIC_NAME, ip, sb.toString());
producer.send(data);
count++;
}
producer.close();
} public void run() {
sendData();
} public static void main(String[] args) {
new ClusterProducer().sendData();
}
}

定于Consumer获取端,获取相应topic的数据:

public class Consumerextends Thread {
private static final Log log =LogFactory.getLog(Consumer.class);
private final ConsumerConnector consumer;
private final String topic; public Consumer(String topic) {
consumer =kafka.consumer.Consumer.createJavaConsumerConnector(
createConsumerConfig());
this.topic = topic;
} private static ConsumerConfigcreateConsumerConfig() {
Properties props = new Properties();
props.put("zookeeper.connect", KafkaProperties.zkConnect);
props.put("group.id",KafkaProperties.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 void run() {
Map<String, Integer>topicCountMap = new HashMap<String, Integer>();
topicCountMap.put(topic, newInteger(1));
Map<String,List<KafkaStream<byte[], byte[]>>> consumerMap =consumer.createMessageStreams(topicCountMap);
KafkaStream<byte[], byte[]>stream = consumerMap.get(topic).get(0);
ConsumerIterator<byte[], byte[]>it = stream.iterator();
while (it.hasNext()) {
log.info("+message: " +new String(it.next().message()));
}
} public static void main(String[] args) {
Consumer client = new Consumer("cluster_statistics_topic");
client.

辅助类:

public interface PropertiesSettings {

    final static String CONSUMER_FILE_NAME = "consumer.properties";
final static String PRODUCER_FILE_NAME = "producer.properties";
final static String TOPIC_NAME = "cluster_statistics_topic";
final static String TOPIC_A = "cluster_statistics_topic_A";
}

package com.kafka.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; /**
* @author JohnLiu
* @version 0.1.0
* @date 2014/8/27
*/
public class PropertiesParser { private static final Log log = LogFactory.getLog(PropertiesParser.class);
/* properties file type */
Properties props = null; /* constructor method*/
public PropertiesParser(Properties props) {
this.props = props;
} /**
* Get the trimmed String value of the property with the given
* <code>name</code>. If the value the empty String (after
* trimming), then it returns null.
*/
public String getStringProperty(String name) {
return getStringProperty(name, null);
} /**
* Get the trimmed String value of the property with the given
* <code>name</code> or the given default value if the value is
* null or empty after trimming.
*/
public String getStringProperty(String name, String def) {
String val = props.getProperty(name, def);
if (val == null) {
return def;
} val = val.trim(); return (val.length() == 0) ? def : val;
} private Properties loadPropertiesFile() {
Properties props = new Properties();
InputStream in;
ClassLoader cl = getClass().getClassLoader();
if (cl == null)
cl = findClassloader();
if (cl == null)
try {
throw new ProcessingException("Unable to find a class loader on the current thread or class.");
} catch (ProcessingException e) {
e.printStackTrace();
}
in = cl.getResourceAsStream(PropertiesSettings.CONSUMER_FILE_NAME);
try {
props.load(in);
} catch (IOException ioe) {
log.error("can't load " + PropertiesSettings.CONSUMER_FILE_NAME, ioe);
}
return props;
} private ClassLoader findClassloader() {
// work-around set context loader for windows-service started jvms (QUARTZ-748)
if (Thread.currentThread().getContextClassLoader() == null && getClass().getClassLoader() != null) {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
}
return Thread.currentThread().getContextClassLoader();
} public static Properties getProperties(final String fileName) {
Properties props = new Properties();
InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(fileName);
try {
props.load(in);
} catch (IOException ioe) {
log.error("can't load " + fileName, ioe);
}
return props;
}
}

配置參数文件consumer.properties:

zookeeper.connect=bigdata09:2181,bigdata08:2181,bigdata07:2181
group.id=cluster_group
zookeeper.session.timeout.ms=400
zookeeper.sync.time.ms=200
auto.commit.interval.ms=1000

配置參数文件producer.properties:

metadata.broker.list=bigdata09:9092,bigdata08:9092,bigdata07:9092
serializer.class=kafka.serializer.StringEncoder
#partitioner.class=com.kafka.producer.SimplePartitioner
request.required.acks=1

分别运行上面的代码,能够发送或者得到相应topic信息。

Enjoy yourself!(*^__^*) ……

Kafka编程实例的更多相关文章

  1. 基于Java+SparkStreaming整合kafka编程

    一.下载依赖jar包 具体可以参考:SparkStreaming整合kafka编程 二.创建Java工程 太简单,略. 三.实际例子 spark的安装包里面有好多例子,具体路径:spark-2.1.1 ...

  2. PHP多进程编程实例

    这篇文章主要介绍了PHP多进程编程实例,本文讲解的是在Linux下实现PHP多进程编程,需要的朋友可以参考下 羡慕火影忍者里鸣人的影分身么?没错,PHP程序是可以开动影分身的!想完成任务,又觉得一个进 ...

  3. c#摄像头编程实例 (转)

    c#摄像头编程实例 摄像头编程 安装摄像头后,一般可以找到一个avicap32.dll文件 这是一个关于设想头的类 using  system;using  System.Runtime.Intero ...

  4. JAX-RS 2.0 REST客户端编程实例

    JAX-RS 2.0 REST客户端编程实例 2014/01/28 | 分类: 基础技术, 教程 | 0 条评论 | 标签: JAX-RS, RESTFUL 分享到:3 本文由 ImportNew - ...

  5. Android studio 下JNI编程实例并生成so库

    Android studio 下JNI编程实例并生成so库 因为公司需要为Android相机做美颜等图像后期处理,需要使用JNI编程,最近学了下JNI,并且在Android Studio下实现了一个小 ...

  6. hadoop2.2编程:使用MapReduce编程实例(转)

    原文链接:http://www.cnblogs.com/xia520pi/archive/2012/06/04/2534533.html 从网上搜到的一篇hadoop的编程实例,对于初学者真是帮助太大 ...

  7. python学习_数据处理编程实例(二)

    在上一节python学习_数据处理编程实例(二)的基础上数据发生了变化,文件中除了学生的成绩外,新增了学生姓名和出生年月的信息,因此将要成变成:分别根据姓名输出每个学生的无重复的前三个最好成绩和出生年 ...

  8. 请求转发:MVC设计模式、细节、请求域属性的编程实例、请求重定向和请求转发的区别

      请求转发:MVC设计模式.细节.请求域属性的编程实例.请求重定向和请求转发的区别 MVC设计模式将一次请求的响应过程分成三个功能模块(一般称之为层)来协同完成,这三个模块分别是Model(模型层) ...

  9. Python进阶:函数式编程实例(附代码)

    Python进阶:函数式编程实例(附代码) 上篇文章"几个小例子告诉你, 一行Python代码能干哪些事 -- 知乎专栏"中用到了一些列表解析.生成器.map.filter.lam ...

随机推荐

  1. Elasticsearch之CURL命令的mget查询

    我这里, 再,创建一个zhouls2的索引库. [hadoop@master elasticsearch-]$ curl -XPUT 'http://master:9200/zhouls2/' {]$ ...

  2. MVC系列学习(十)-生成URL与表单

    本次学习,在路由配置信息中,有两个路由规则,在网站第一次启动的时候,注册了两个路由表 1.动态生成url A.在路由规则中,因为Default在前面,所以最新找到该路由表,此时不管 自己定义的控制器名 ...

  3. Serializable和Parcelable的简单介绍

    Serializable和Pacelable接口可以完成对象的序列化过程,当我们需要通过Intent和Binder传输数据时就需要使用Parcelable或者Serializable. Seriali ...

  4. JS——event

    触发DOM上的某个事件时,会产生一个事件对象event,这个对象中包含着所有与事件有关的信息: 普通浏览器支持 event(传参),IE678支持 window.event(无参),兼容写法: < ...

  5. JS——模拟百度搜索

    注意事项: 1.for循环移除子节点时,其长度是变化的 2.在文档流中,input.img.p等标签与其他标签有3px的距离,利用左浮动,可以消除3px距离 3.背景图片定位时,第一个值是x轴方向的值 ...

  6. js分页插件

    //分页插件1function showView(option) {    //参数定义id,页容量,当前页,总数,页总数    var id = option.id,         pageSiz ...

  7. 体验SqlServer Express 2014

    想使用SQLServer Express记录一些数据,但使用起来并不令人愉快.SQLServer Express是一个免费的可用数据库,但似乎设置了一些门槛,多少显得并不真心实意.抛开版本(技术)限制 ...

  8. 【sqli-labs】 less53 GET -Blind based -Order By Clause -String -Stacked injection(GET型基于盲注的字符型Order By从句堆叠注入)

    http://192.168.136.128/sqli-labs-master/Less-53/?sort=1';insert into users(id,username,password) val ...

  9. C# 执行sql语句批量更新

    int x = db.Database.ExecuteSqlCommand(string.Format("update T_Pension SET UnitType = '{0}' WHER ...

  10. Django的文件下载

    在实际的项目中很多时候需要用到下载功能,如导excel.pdf或者文件下载,当然你可以使用web服务自己搭建可以用于下载的资源服务器,如nginx,这里我们主要介绍django中的文件下载. 我们这里 ...