编程

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. 大话设计模式--DI(依赖注入)

    1.背景 想象一个场景:有个功能通过某个参数决定了路由到不同的方法上或者几个方法模块可以自由搭配,咋办?一般人会对每个方法写一个helper(比如SendMessageForEmail.SendMes ...

  2. canvas烟花锦集

    canvas可以实现不同动画效果,本文主要记录几种不同节日烟花效果实现. 实现一 效果地址 html <canvas id="canvas"></canvas&g ...

  3. 阿里云虚拟主机针对恶意频繁攻击式访问造成CPU爆满的解决方法

    最近网站CPU经常爆满,到阿里云提交了工单,工程师给我的处理意见:   您好,虚拟主机CPU占用比较高通常这种情况有两种可能:   一是网站应用程序代码逻辑较复杂,或业务架构效率比较低,在请求了某个网 ...

  4. Caffe2:python -m caffe2.python.operator_test.relu_op_test

    1. 进行语句测试时候,出现问题, 设置环境变量CUDA_VISIBLE_DEVICES 参考: cuda设置指定可见方法 在/etc/profile文件或者-/.bashrc末尾添加以下行: exp ...

  5. ajax请求参数的格式

    因为多写了一个contentType=“text/html”,请求的时候,参数总是转成了url&拼接的格式,导致请求不成功,调试了老半天 这个也是奇怪,为什么post只能接收json格式的数据 ...

  6. css3 animation 中的 steps

    steps Specifies a stepping function, described above, taking two parameters. The first parameter spe ...

  7. python学习笔记--关于函数的那点事1

    函数参数 1.位置参数 类似于java函数的基本参数,按照顺序和结构定义参数 2.默认参数 def method(param,defaultParam=defaultValue) 调用时,可以调用me ...

  8. final关键字用法

    Java关键字final有“这是无法改变的”或者“终态的”含义,它可以修饰非抽象类.非抽象类成员方法和变量. final类不能被继承,没有子类,final类中的方法默认是final的. final方法 ...

  9. maxtrid 3D视差

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  10. Fang Fang HDU - 5455 (思维题)

    Fang Fang says she wants to be remembered. I promise her. We define the sequence FF of strings. F0 = ...