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. tomcat改端口的一些问题

    cmd运行netstat -anp查看端口使用情况,找到被占用端口的PID

  2. Ubuntu14.04浏览器Firefox安装flash播放插件

    sudo apt-get update sudo apt-get install flashplugin-nonfree ================= 类飞秋软件 sudo apt-get in ...

  3. 关于Java集合

    之前关于java集合认识,虽然理解,但是总是忘记关键点,今明两天写一篇关于集合的随笔

  4. Tiny6410之控制icache驱动

    什么是cache:    基于程序访问的局限性,在主存和CPU通用寄存器之间设置了一类高速的.容量较小的存储器,把正在执行的指令地址附件的一部分指令或数据从主存调入这类存储器,供CPU 在一段时间内使 ...

  5. tabBar 选中默认蓝色 ,取消选中(自定义)

    - (void)viewDidLoad { [super viewDidLoad]; //    [self _initSubViewControllers]; //    [self _custom ...

  6. angular中的jsonp记录

    angular的正常机制采用引入$http服务的形式进行 get post等的访问.但是在跨域访问的时候就需要采用jsonp了. 不废话,直接上示例和引用原文地址: 比如访问地址为 http://ur ...

  7. javascript单例模式(懒汉 饿汉)

    第一种:懒汉模式 var Singleton=(function(){ var instantiated; //比较懒,在类加载时,不创建实例,因此类加载速度快,但运行时获取对象的速度慢 functi ...

  8. 异步设备IO:OVERLAPPED和IOCompletionPort

    异步设备IO:OVERLAPPED和IOCompletionPort 本文内容为<windows核心编程>第10章内容的总结,仅记录一些本人感兴趣的内容. 1:OVERLAPPED &qu ...

  9. B/S、C/S区别

    [B/S.C/S C/S (Client/Server客户端服务器) B/S (Brower/Server浏览器服务器)  区别 1.硬件环境不同: C/S 一般建立在专用的网络上, 小范围里的网络环 ...

  10. OpenVPN GUI: "No TAP-WIN32 adapters on this system"

    找到C:\Program Files\TAP-Windows\bin 管理员身份运行: deltapall.bat addtap.bat