设为首页 收藏本站
查看: 1156|回复: 0

[经验分享] 【Kakfa五】Kafka Producer和Consumer基本使用

[复制链接]

尚未签到

发表于 2017-5-23 18:19:13 | 显示全部楼层 |阅读模式
0.Kafka服务器的配置
  一个Broker,
  一个Topic
  Topic中只有一个Partition()

 

1. Producer:

package kafka.examples.producers;

import kafka.producer.KeyedMessage;
import kafka.javaapi.producer.Producer;
import kafka.producer.ProducerConfig;
import java.util.Properties;
public class SimpleProducer {
private static Producer<Integer, String> producer;
private static final Properties props = new Properties();
///ProducerConfig没有关于Zookeeper的配置信息
static {
props.put("broker.list", "192.168.26.140:9092");
/*metadata.broker.list is for bootstrapping and the producer will only use it for getting
metadata (topics, partitions and replicas). The socket connections for
sending the actual data will be established based on the broker
information returned in the metadata. The format is
host1:port1,host2:port2, and the list can be a subset of brokers or a
VIP pointing to a subset of brokers.*/
props.put("metadata.broker.list", "192.168.26.140:9092");
/*The serializer class for messages. The default encoder(kafka.serializer.DefaultEncoder) takes a byte[] and returns the same byte[].*/
props.put("serializer.class", "kafka.serializer.StringEncoder");
/**/
props.put("request.required.acks", "1");
producer = new Producer<Integer, String>(new ProducerConfig(props));
}
public static void main(String[] args) {
String topic = "learn.topic";
String messageStr = "This is a simple message from JavaAPI Producer2";
///Key如何生成的?
KeyedMessage<Integer, String> data = new KeyedMessage<Integer,String>(topic, messageStr);
producer.send(data);
producer.close();
}
}
  关于request.required.acks:
  This value controls when a produce request is considered completed. Specifically, how many other brokers must have committed the data to their log and acknowledged this to the leader? Typical values are


  • 0, which means that the producer never waits for an acknowledgement from the broker (the same behavior as 0.7). This option provides the lowest latency but the weakest durability guarantees (some data will be lost when a server fails).
  • 1, which means that the producer gets an acknowledgement after the leader replica has received the data. This option provides better durability as the client waits until the server acknowledges the request as successful (only messages that were written to the now-dead leader but not yet replicated will be lost).
  • -1, The producer gets an acknowledgement after all in-sync replicas have received the data. This option provides the greatest level of durability. However, it does not completely eliminate the risk of message loss because the number of in sync replicas may, in rare cases, shrink to 1. If you want to ensure that some minimum number of replicas (typically a majority) receive a write, then you must set the topic-level min.insync.replicas setting. Please read the Replication section of the design documentation for a more in-depth discussion.
  关于KeyedMessage:

/**
* A topic, key, and value.
* If a partition key is provided it will override the key for the purpose of partitioning but will not be stored.
*/
case class KeyedMessage[K, V](val topic: String, val key: K, val partKey: Any, val message: V) {
if(topic == null)
throw new IllegalArgumentException("Topic cannot be null.")
def this(topic: String, message: V) = this(topic, null.asInstanceOf[K], null, message)
def this(topic: String, key: K, message: V) = this(topic, key, key, message)
//分区键,如果没有,是什么行为
def partitionKey = {
if(partKey != null)
partKey
else if(hasKey)
key
else
null  
}
def hasKey = key != null
}

2. Consumer

package kafka.examples.consumers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import kafka.consumer.Consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
public class SimpleHLConsumer {
private final ConsumerConnector consumer;
private final String topic;
public SimpleHLConsumer(String zookeeper, String groupId, String
topic) {
///Consumer的属性配置
Properties props = new Properties();
props.put("zookeeper.connect", zookeeper);
//consumer group id
props.put("group.id", groupId);
/*
ZooKeeper session timeout. If the server fails to heartbeat to ZooKeeper
within this period of time it is considered dead. If you set this too
low the server may be falsely considered dead; if you set it too high it
may take too long to recognize a truly dead server.
*/
props.put("zookeeper.session.timeout.ms", "500"); //默认6秒
///How far a ZK follower can be behind a ZK leader.默认两秒
props.put("zookeeper.sync.time.ms", "250");
///offset自动提交的时间间隔
props.put("auto.commit.interval.ms", "1000");
consumer = Consumer.createJavaConsumerConnector(new ConsumerConfig(props));
this.topic = topic;
}
public void doConsume() {
Map<String, Integer> topicCount = new HashMap<String, Integer>();
// Define single thread for topic
topicCount.put(topic, new Integer(1));
Map<String, List<KafkaStream<byte[], byte[]>>> consumerStreams = consumer.createMessageStreams(topicCount);
//KafkaStream是一个BlockingQueue
List<KafkaStream<byte[], byte[]>> streams = consumerStreams.get(topic);
///有几个线程,就会有几个Kafka Stream
for (final KafkaStream stream : streams) {
/**
* An iterator that blocks until a value can be read from the supplied queue.
* The iterator takes a shutdownCommand object which can be added to the queue to trigger a shutdown
*
*/
ConsumerIterator<byte[], byte[]> consumerIte = stream.iterator();
///阻塞在hasNext等待消息到来
while (consumerIte.hasNext()) {
System.out.println("Message from Single Topic :: " + new String(consumerIte.next().message()));
}
}
if (consumer != null) {
consumer.shutdown();
}
}
public static void main(String[] args) {
String topic = "learn.topic";
////learn.topic.consumers.group是消费者群组,不需要预先定义,但是会记录到Zookeeper中
SimpleHLConsumer simpleHLConsumer = new SimpleHLConsumer("192.168.26.140:2181", "learn.topic.consumers.group", topic);
simpleHLConsumer.doConsume();
}
}


3. 注意的问题:
  因为Kafka服务器和Producer、Consumer不在同一个机器上,因此在配置Kafka中的Zookeeper连接信息以及server.properties中的host.name时,需要指定具体的IP,不能使用localhost

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-379970-1-1.html 上篇帖子: 【Kakfa五】Kafka Producer和Consumer基本使用 下篇帖子: RabbitMQ和kafka从几个角度简单的对比
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表