Kafka编程实例
编程
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编程实例的更多相关文章
- 基于Java+SparkStreaming整合kafka编程
一.下载依赖jar包 具体可以参考:SparkStreaming整合kafka编程 二.创建Java工程 太简单,略. 三.实际例子 spark的安装包里面有好多例子,具体路径:spark-2.1.1 ...
- PHP多进程编程实例
这篇文章主要介绍了PHP多进程编程实例,本文讲解的是在Linux下实现PHP多进程编程,需要的朋友可以参考下 羡慕火影忍者里鸣人的影分身么?没错,PHP程序是可以开动影分身的!想完成任务,又觉得一个进 ...
- c#摄像头编程实例 (转)
c#摄像头编程实例 摄像头编程 安装摄像头后,一般可以找到一个avicap32.dll文件 这是一个关于设想头的类 using system;using System.Runtime.Intero ...
- JAX-RS 2.0 REST客户端编程实例
JAX-RS 2.0 REST客户端编程实例 2014/01/28 | 分类: 基础技术, 教程 | 0 条评论 | 标签: JAX-RS, RESTFUL 分享到:3 本文由 ImportNew - ...
- Android studio 下JNI编程实例并生成so库
Android studio 下JNI编程实例并生成so库 因为公司需要为Android相机做美颜等图像后期处理,需要使用JNI编程,最近学了下JNI,并且在Android Studio下实现了一个小 ...
- hadoop2.2编程:使用MapReduce编程实例(转)
原文链接:http://www.cnblogs.com/xia520pi/archive/2012/06/04/2534533.html 从网上搜到的一篇hadoop的编程实例,对于初学者真是帮助太大 ...
- python学习_数据处理编程实例(二)
在上一节python学习_数据处理编程实例(二)的基础上数据发生了变化,文件中除了学生的成绩外,新增了学生姓名和出生年月的信息,因此将要成变成:分别根据姓名输出每个学生的无重复的前三个最好成绩和出生年 ...
- 请求转发:MVC设计模式、细节、请求域属性的编程实例、请求重定向和请求转发的区别
请求转发:MVC设计模式.细节.请求域属性的编程实例.请求重定向和请求转发的区别 MVC设计模式将一次请求的响应过程分成三个功能模块(一般称之为层)来协同完成,这三个模块分别是Model(模型层) ...
- Python进阶:函数式编程实例(附代码)
Python进阶:函数式编程实例(附代码) 上篇文章"几个小例子告诉你, 一行Python代码能干哪些事 -- 知乎专栏"中用到了一些列表解析.生成器.map.filter.lam ...
随机推荐
- lua_string_pattern
两大特点: 1. string库中所有的字符索引从前往后是1,2,...;从后往前是-1,-2,... 2. string库中所有的function都不会直接操作字符串,而是返回一个新的字符串. 库函 ...
- 使用XUL开发跨平台桌面应用
先上图: 现在使用html,css,js开发桌面的优势越来越明显了,硬件性能的不断提升,人力成本越发昂贵,用户对界面要求越来越高,全球化下企业间的竞争越发激烈. 桌面软件50%+的工作量都在界面开发这 ...
- mysql中返回当前时间的函数或者常量
引用:http://blog.sina.com.cn/s/blog_6d39dc6f0100m7eo.html 1.1 获得当前日期+时间(date + time)函数:now() 除了 now() ...
- 关于Adaper的相关用法
使用BaseAdapter的话需要重载四个方法: getCount getItem getItemId getView getView是用来刷新它所在的ListView的.在每一次item从屏幕外滑进 ...
- MYSQL 使用自定义表变量
mysql 用户自定义表变量,ENGINE=MyISAM DEFAULT CHARSET=gb2312; 制定编码方式,防止乱码 DROP TABLE IF EXISTS p_temp; creat ...
- centOS7卸载google-chrome
参考: https://www.jianshu.com/p/39d0b8f578d9
- smtplib.SMTPDataError: (554, b'DT:SPM 126 smtp
报错信息 smtplib.SMTPDataError: (554, b'DT:SPM 126 smtp7,DsmowAA3uguL7e1cyvkyFw--.22553S3 1559096715,ple ...
- 想学Python?这里有一个最全面的职位分析
Python从2015年开始,一直处于火爆的趋势,目前Python工程师超越Java.Web前端等岗位,起薪在15K左右,目前不管是小公司还是知名大公司都在热招中. 当然,每个城市对岗位的需求也不尽相 ...
- SpringBoot启动报jdbc连接池错误
如图,启动报连接池错误 项目中没有使用任何连接池,以为没用连接池的原因,所以配置了druid,一开始可以正常启动,但后来重启项目时仍旧报同样的错.网上找了资料,url中加useSSL=false,显式 ...
- 【VIP视频网站项目三】项目框架搭建、项目路由配置、数据库表结构设计
一.项目路由的设计 目前项目代码已经全部开源:项目地址:https://github.com/xiugangzhang/vip.github.io 视频网站前台页面路由设计 路由 请求方法 模板 作用 ...