kafka是一个消息中间件,用于各个系统之间传递消息,并且消息可持久化!

可以认为是队列模型,也可以看作是生产者消费着模型;

简单的生产者消费者客户端代码如下:

package com.pt.util.kafka;

import java.util.Date;
import java.util.Properties; import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig; public class MyProducer {
public static void sendMsg(String msg) {
Properties props = new Properties();
//brokers list
props.put("metadata.broker.list", "192.168.91.231:9092,192.168.91.231:9093");
/* *
* the serializer when preparing the message for transmission to the Broker
* Note that the encoder must accept the same type
* as defined in the KeyedMessage object in the next step.
*
*/
props.put("serializer.class", "kafka.serializer.StringEncoder");
/* *
* defines what class to use to determine
* which Partition in the Topic the message is to be sent to
*/
props.put("partitioner.class", "example.producer.SimplePartitioner");
/* *
* tells Kafka that you want your Producer to require an
* acknowledgement from the Broker that the message was received
*/
props.put("request.required.acks", "1"); ProducerConfig config = new ProducerConfig(props);
/*
* Note that the Producer is a Java Generic and you need to tell it the type of two parameters.
* The first is the type of the Partition key, the second the type of the message.
*/
Producer<String, String> producer = new Producer<String, String>(config); long runtime = new Date().getTime();
String ip = "192.168.91.231";
/*
* The “panteng” is the Topic to write to.
* Here we are passing the IP as the partition key.
* Note that if you do not include a key,
* even if you've defined a partitioner class, Kafka will assign the message to a random partition.
*/
KeyedMessage<String, String> data = new KeyedMessage<String, String>(
"panteng", ip, msg);
producer.send(data);
producer.close();
}
}

Producer,java

package cn.outofmemory.kafka;

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 final ConsumerConnector consumer; public KafkaConsumer() {
Properties props = new Properties();
//zookeeper 配置
props.put("zookeeper.connect", "192.168.91.231: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);
} public void consume() {
Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
topicCountMap.put("panteng", 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("panteng").get(0);
ConsumerIterator<String, String> it = stream.iterator();
while (it.hasNext())
System.out.println(it.next().message());
} public void stop(){
try {
consumer.shutdown();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} }
public static void main(String[] args) {
new KafkaConsumer().consume();
}
}

Consumer.java

kafka消息中间件及java示例的更多相关文章

  1. Kafka+Storm+HDFS 整合示例

    消息通过各种方式进入到Kafka消息中间件,比如可以通过使用Flume来收集日志数据,然后在Kafka中路由暂存,然后再由实时计算程序Storm做实时分析,最后将结果保存在HDFS中,这时我们就需要将 ...

  2. KClient——kafka消息中间件源码解读

    目录 kclient消息中间件 kclient-processor top.ninwoo.kclient.app.KClientApplication top.ninwoo.kclient.app.K ...

  3. 【Apache Kafka】二、Kafka安装及简单示例

    (一)Apache Kafka安装 1.安装环境与前提条件   安装环境:Ubuntu16.04   前提条件: ubuntu系统下安装好jdk 1.8以上版本,正确配置环境变量 ubuntu系统下安 ...

  4. 课程作业01:模仿JavaAppArguments.java示例,编写一个程序,此程序从命令行接收多个数字,求和之后输出结果。

    1.设计思想: 首先是从JavaAppArguments.java示例开始,此示例已打印参数,定义数字 之和和作为存储单位的整型,然后将输入参数的字符串转化为整型,之后求和即可. 2.程序流程图: 3 ...

  5. 左右JAVA示例代码事件分发和监督机制来实现-绝对原创有用

    文章标题:左右JAVA示例代码事件分发和监督机制来实现 文章地址: http://blog.csdn.net/5iasp/article/details/37054171 作者: javaboy201 ...

  6. Spark 用户自定义函数 Java 示例

    Spark UDF Java 示例 在这篇文章中提到了用Spark做用户昵称文本聚类分析,聚类需要选定K个中心点,然后迭代计算其他样本点到中心点的距离.由于中文文字分词之后(n-gram)再加上昵称允 ...

  7. FATAL Fatal error during KafkaServerStable startup. Prepare to shutdown (kafka.server.KafkaServerStartable) java.io.FileNotFoundException: /tmp/kafka-logs/.lock (Permission denied)

    1.启动kafka的时候,报错如下所示: [-- ::,] INFO zookeeper state changed (SyncConnected) (org.I0Itec.zkclient.ZkCl ...

  8. kafka学习之-java api测试

    1.配置 package com.storm.storm_my.kafka; /** * * @author Peng.Li * */ public class KafkaConfigApiConst ...

  9. kafka启动报java.net.UnknownHostException

    kafka启动报java.net.UnknownHostException 参考资料: 1.https://blog.csdn.net/zdxiq000/article/details/6258765 ...

随机推荐

  1. 利用before、after制作提示框

    提示框由两部分组成,框+箭头,箭头则利用伪元素before.after写成. 根据提示框的样式可以看出,上面的箭头由两部分组成:灰色大箭头+蓝色小箭头,蓝色嵌套在灰色里面,于是箭头就有了边框,整体搭配 ...

  2. @classmethod及@staticmethod方法浅析【python】

    目前对于python中@classmethod 类方法和@staticmethod静态方法的有了一定的认识,之后有进一步的认识后继续记录. @classmethod :是和一个class类相关的方法, ...

  3. python(序列递归)【输出原子级别元素。。。】

    晚上回去复习下原来的资料,返现Codebook中有个关于“展开一个嵌套序列”的话题. 任务说明:序列中的子项可能是序列,子序列的子项仍可能是序列,以此类推,则序列嵌套可以达到任意的深度.需要循环遍历一 ...

  4. WinForm ListView

    今天,我学习了公共控件中的ListView的内容. 首先,在利用ListView布置界面时,有以下三个方面: 1.视图:            在其右上方小箭头点击将视图改为Details:或者右键属 ...

  5. 【IE6的疯狂之二】IE6中PNG Alpha透明(全集)

    ie7,fireofx,opera,及至webkit内核的chrome ,safari….. 这些浏览器均支持png的Alpha透明. 很多人说IE6不支持PNG透明,其实IE支持100%透明的PNG ...

  6. linux面试

    1.用户进程间通信主要哪几种方式 (1)管道(Pipe):管道可用于具有亲缘关系进程间的通信,允许一个进程和另一个与它有共同祖先的进程之间进行通信.(2)命名管道(named pipe):命名管道克服 ...

  7. python 如何读取大文件

    一般的读取文件的方法: with open(file_path, "r") as f: print f.read() 或者 with open(file_path,"r& ...

  8. 架设自己的FTP服务器 Serv-U详细配置图文教程

    转自:http://www.jb51.net/article/31635.htm 所有不是很要求安全的情况下是可以用serv_U的,当然我们也可以通过一些设置,保证serv_u安全运行.这里就分享下s ...

  9. 京东的SSO

    京东的sso流程: 初始访问状态: cookies: http请求: 1.在首页点击登陆,跳转至passport.360buy.com,给予验证cookie alc(可以试试在提交登陆信息前删除该co ...

  10. 一键批量ping任意ip段的存活主机

    =======================by me===================================== @echo offecho.color FC for /f %%i ...