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. 基于AFN的多张图片上传

    不废话,直接上代码 NSString *urlString = [NSString stringWithFormat:@"http://192.168.1.166:8080/Discipli ...

  2. Error(10028)

    两个进程里都有同一个条件判断的话,会产生并行信号冲突的问题. 同一个信号不允许在多个进程中赋值,否则则为多驱动. 进程的并行性决定了多进程不同能对同一个对象进行赋值.

  3. 搭建git代码服务器

    在代码管理中,通常需要使用版本管理工具,git就是一个不错的选择,这里简单罗列一下git服务器的搭建过程. 1. 安装git工具包 2. 初始化git库:在代码服务器上,通常只需要创建一个不含有工作目 ...

  4. QCMediaPlayer mediaplayer NOT present(android)

    出现了“QCMediaPlayer mediaplayer NOT present”这个错误!!!我的手机是小米手机2,我给它刷机刷到了Android 4.4.4,后来我学长是这样解决的:case R ...

  5. Maven pom项目部署

    maven控制台运行程序 <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec- ...

  6. neutron的agents

    一般agent的模块主要由Neutron api.core plugin(如linux bridge plugin,ovs plugin等).XX agent scheduler.XX agent.X ...

  7. Namenode写Journalnode超时,导致Namenode挂掉的问题

    昨天还好好的集群,今天早上来看又挂掉了,还好是家里的测试服务器集群... 首先,查看了Namenode的状态,发现两台Namenode只剩下一台了,赶紧到挂了的那台去查看了logs下的日志: -- : ...

  8. 利用LinkedList实现洗牌功能

    分2步: 1.生成扑克牌. 2.洗牌. package com.dongbin.collection; import java.util.LinkedList; import java.util.Ra ...

  9. 使用PHP连接redis后,timeout连接太多的解决方案

    这个问题,大家在使用php redis之后肯定都会遇到.所以本菜本着虚心求教的原则,又在网上四处求教.得到的答案,无非是以下两种: 1.redis没有主动close. 事后发现,这个答案纯属以讹传讹, ...

  10. RMIC命令提示找不到类的问题

    问题环境: RMI服务类已经写好. 目录结构: -- A ----- B -------- C ------------- RMIImpl.class RMIImpl.java : package B ...