kafka环境搭建及demo
来源:互联网 发布:windows黑体字体下载 编辑:程序博客网 时间:2024/06/05 17:05
- 概述
- 文件下载
- 系统环境搭建和配置
- kafka demo
参考
概述
- kafka是一个分布式的消息缓存系统
- kafka集群中的服务器都叫做broker
- kafka有两类客户端,一类叫producer(消息生产者),一类叫做consumer(消息消费者),客户端和broker服务器之间采用tcp协议连接
- kafka中不同业务系统的消息可以通过topic进行区分,而且每一个消息topic都会被分区,以分担消息读写的负载
- 每一个分区都可以有多个副本,以防止数据的丢失
- 某一个分区中的数据如果需要更新,都必须通过该分区所有副本中的leader来更新
- 消费者可以分组,比如有两个消费者组A和B,共同消费一个topic:order_info,A和B所消费的消息不会重复 ,比如 order_info 中有100个消息,每个消息有一个id,编号从0-99,那么,如果A组消费0-49号,B组就消费50-99号
- 消费者在具体消费某个topic中的消息时,可以指定起始偏移量
文件下载
- zookeeper下载
下载地址:http://apache.fayea.com/zookeeper/zookeeper-3.3.6/zookeeper-3.3.6.tar.gz - kafka下载
地址:https://mirrors.tuna.tsinghua.edu.cn/apache/kafka/0.11.0.0/kafka_2.11-0.11.0.0.tgz
- zookeeper下载
系统环境搭建和配置
- java7配置省略
- zookeeper配置(此处略,参考:http://blog.csdn.net/lxf20054658/article/details/74452755)
- kafka配置
- 上传kafka_2.11-0.11.0.0.tgz到centos服务器
- 解压,tar -zxvf kafka_2.11-0.11.0.0.tgz,mv kafka_2.11-0.11.0.0 /usr/lib/apache-kafka
- 配置,cd /usr/lib/apache-kafka/config,vi server.properties,配置示例(参考颜色标注的地方即可):
# Licensed to the Apache Software Foundation (ASF) under one or more# contributor license agreements. See the NOTICE file distributed with# this work for additional information regarding copyright ownership.# The ASF licenses this file to You under the Apache License, Version 2.0# (the "License"); you may not use this file except in compliance with# the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# see kafka.server.KafkaConfig for additional details and defaults############################# Server Basics ############################## The id of the broker. This must be set to a unique integer for each broker.broker.id=1# Switch to enable topic deletion or not, default value is false#delete.topic.enable=true############################# Socket Server Settings ############################## The address the socket server listens on. It will get the value returned from# java.net.InetAddress.getCanonicalHostName() if not configured.# FORMAT:# listeners = listener_name://host_name:port# EXAMPLE:# listeners = PLAINTEXT://your.host.name:9092#listeners=PLAINTEXT://:9092# Hostname and port the broker will advertise to producers and consumers. If not set,# it uses the value for "listeners" if configured. Otherwise, it will use the value# returned from java.net.InetAddress.getCanonicalHostName().#advertised.listeners=PLAINTEXT://your.host.name:9092# Maps listener names to security protocols, the default is for them to be the same. See the config documentation for more details#listener.security.protocol.map=PLAINTEXT:PLAINTEXT,SSL:SSL,SASL_PLAINTEXT:SASL_PLAINTEXT,SASL_SSL:SASL_SSL# The number of threads that the server uses for receiving requests from the network and sending responses to the networknum.network.threads=3# The number of threads that the server uses for processing requests, which may include disk I/Onum.io.threads=8# The send buffer (SO_SNDBUF) used by the socket serversocket.send.buffer.bytes=102400# The receive buffer (SO_RCVBUF) used by the socket serversocket.receive.buffer.bytes=102400# The maximum size of a request that the socket server will accept (protection against OOM)socket.request.max.bytes=104857600############################# Log Basics ############################## A comma seperated list of directories under which to store log fileslog.dirs=/tmp/kafka-logs# The default number of log partitions per topic. More partitions allow greater# parallelism for consumption, but this will also result in more files across# the brokers.num.partitions=1# The number of threads per data directory to be used for log recovery at startup and flushing at shutdown.# This value is recommended to be increased for installations with data dirs located in RAID array.num.recovery.threads.per.data.dir=1############################# Internal Topic Settings ############################## The replication factor for the group metadata internal topics "__consumer_offsets" and "__transaction_state"# For anything other than development testing, a value greater than 1 is recommended for to ensure availability such as 3.offsets.topic.replication.factor=1transaction.state.log.replication.factor=1transaction.state.log.min.isr=1############################# Log Flush Policy ############################## Messages are immediately written to the filesystem but by default we only fsync() to sync# the OS cache lazily. The following configurations control the flush of data to disk.# There are a few important trade-offs here:# 1. Durability: Unflushed data may be lost if you are not using replication.# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush.# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks.# The settings below allow one to configure the flush policy to flush data after a period of time or# every N messages (or both). This can be done globally and overridden on a per-topic basis.# The number of messages to accept before forcing a flush of data to disk#log.flush.interval.messages=10000# The maximum amount of time a message can sit in a log before we force a flush#log.flush.interval.ms=1000############################# Log Retention Policy ############################## The following configurations control the disposal of log segments. The policy can# be set to delete segments after a period of time, or after a given size has accumulated.# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens# from the end of the log.# The minimum age of a log file to be eligible for deletion due to agelog.retention.hours=168# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining# segments don't drop below log.retention.bytes. Functions independently of log.retention.hours.#log.retention.bytes=1073741824# The maximum size of a log segment file. When this size is reached a new log segment will be created.log.segment.bytes=1073741824# The interval at which log segments are checked to see if they can be deleted according# to the retention policieslog.retention.check.interval.ms=300000############################# Zookeeper ############################## Zookeeper connection string (see zookeeper docs for details).# This is a comma separated host:port pairs, each corresponding to a zk# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002".# You can also append an optional chroot string to the urls to specify the# root directory for all kafka znodes.zookeeper.connect=hadooplearn:2181# Timeout in ms for connecting to zookeeperzookeeper.connection.timeout.ms=6000############################# Group Coordinator Settings ############################## The following configuration specifies the time, in milliseconds, that the GroupCoordinator will delay the initial consumer rebalance.# The rebalance will be further delayed by the value of group.initial.rebalance.delay.ms as new members join the group, up to a maximum of max.poll.interval.ms.# The default value for this is 3 seconds.# We override this to 0 here as it makes for a better out-of-the-box experience for development and testing.# However, in production environments the default value of 3 seconds is more suitable as this will help to avoid unnecessary, and potentially expensive, rebalances during application startup.group.initial.rebalance.delay.ms=0
* 启动broker
bin/kafka-server-start.sh config/server.properties
* 在kafka集群中创建一个topic
bin/kafka-topics.sh –create –zookeeper hadooplearn:2181 –replication-factor 1 –partitions 1 –topic order
* 查看topic
bin/kafka-topics.sh –list –zookeeper hadooplearn:2181
* 用一个producer向某一个topic中写入消息(往话题order写消息)
bin/kafka-console-producer.sh –broker-list hadooplearn:9092 –topic order
* 用一个comsumer从某一个topic中读取信息
bin/kafka-console-consumer.sh –zookeeper hadooplearn:2181 –from-beginning –topic order
* 查看一个topic的分区及副本状态信息
bin/kafka-topics.sh –describe –zookeeper hadooplearn:2181 –topic order
1. kafka demo
注:基于kafka_2.11-0.11.0.0.tgz包
生产者:
package cn.itcast.kafka;import java.util.Properties;import org.apache.kafka.clients.producer.KafkaProducer;import org.apache.kafka.clients.producer.Producer;import org.apache.kafka.clients.producer.ProducerRecord;/** * see http://kafka.apache.org/090/javadoc/index.html?org/apache/kafka/clients/producer/KafkaProducer.html * @author xfli * */public class ProducerDemo { /** * @param args */ public static void main(String[] args) { Properties props = new Properties(); props.put("bootstrap.servers", "hadooplearn:9092"); props.put("metadata.broker.list","hadooplearn:9092"); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); Producer<String, String> producer = new KafkaProducer<>(props); // 发送业务消息 // 读取文件 读取内存数据库 读socket端口 for (int i = 1; i <= 100; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } producer.send(new ProducerRecord<String, String>("wordcount", i+" said "+ i + " love you baby for " + i + " times,will you have a nice day with me tomorrow")); } }}
消费者:
package cn.itcast.kafka;import java.util.Arrays;import java.util.Properties;import java.util.concurrent.atomic.AtomicBoolean;import org.apache.kafka.clients.consumer.ConsumerRecord;import org.apache.kafka.clients.consumer.ConsumerRecords;import org.apache.kafka.clients.consumer.KafkaConsumer;import org.apache.kafka.common.errors.WakeupException;/** * see http://kafka.apache.org/090/javadoc/index.html?org/apache/kafka/clients/consumer/KafkaConsumer.html * consumer/KafkaConsumer.html * * @author xfli * */public class ConsumerDemo implements Runnable { private final AtomicBoolean closed = new AtomicBoolean(false); KafkaConsumer<String, String> consumer;// = new KafkaConsumer<>(props); public void run() { try { Properties props = new Properties(); props.put("bootstrap.servers", "hadooplearn:9092"); props.put("group.id", "test"); props.put("enable.auto.commit", "true"); props.put("auto.commit.interval.ms", "1000"); props.put("session.timeout.ms", "30000"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); consumer = new KafkaConsumer<>(props); consumer.subscribe(Arrays.asList("wordcount")); while (!closed.get()) { ConsumerRecords<String, String> records = consumer.poll(10000); // Handle new records for (final ConsumerRecord<String, String> rc : records) { System.out.println("msg=" + rc.value()); } try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (WakeupException e) { // Ignore exception if closing if (!closed.get()) throw e; } finally { consumer.close(); } } // Shutdown hook which can be called from a separate thread public void shutdown() { closed.set(true); consumer.wakeup(); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ConsumerDemo sub1 = new ConsumerDemo(); Thread tsub1 = new Thread(sub1); tsub1.start(); }}
运行结果示例:
msg=56 said 56 love you baby for 56 times,will you have a nice day with me tomorrowmsg=57 said 57 love you baby for 57 times,will you have a nice day with me tomorrowmsg=58 said 58 love you baby for 58 times,will you have a nice day with me tomorrowmsg=59 said 59 love you baby for 59 times,will you have a nice day with me tomorrowmsg=60 said 60 love you baby for 60 times,will you have a nice day with me tomorrowmsg=61 said 61 love you baby for 61 times,will you have a nice day with me tomorrowmsg=62 said 62 love you baby for 62 times,will you have a nice day with me tomorrowmsg=63 said 63 love you baby for 63 times,will you have a nice day with me tomorrowmsg=64 said 64 love you baby for 64 times,will you have a nice day with me tomorrowmsg=65 said 65 love you baby for 65 times,will you have a nice day with me tomorrow
参考:
http://kafka.apache.org/090/javadoc/index.html?org/apache/kafka/clients/producer/KafkaProducer.html
http://kafka.apache.org/090/javadoc/index.html?org/apache/kafka/clients/consumer/KafkaConsumer.html
- kafka环境搭建及demo
- 【Kafka】kafka环境搭建及使用
- 【Kafka】kafka环境搭建及使用
- Kafka介绍及环境搭建
- Kafka基本概念及环境搭建
- Kafka+Storm+HBase项目Demo(2)--Kafka环境搭建
- storm环境搭建及demo
- kafka入门介绍及环境搭建
- 02-kafka环境搭建及测试
- appium java环境搭建及demo
- python-环境搭建及自动化测试Demo
- (一)Spring环境搭建及简单demo
- zookeeper+Dubbo环境搭建及简单Demo
- Hibernate之环境搭建及demo
- Java环境搭建及Demo测试
- Kafka分布式环境搭建
- Kafka分布式环境搭建
- Kafka开发环境搭建
- 用消息队列和消息应用状态表来消除分布式事务
- mysql-5.5.56版本(二进制包安装)-自定义安装路径
- NMT开源代码
- nginx-1.12.0版本(编译安装)-自定义安装路径
- php-7.0.18版本(编译安装)-自定义安装路径
- kafka环境搭建及demo
- 67 linux内核里的framebuffer设备驱动模型
- git参考资料,及自己整理的命令
- Ngx_lua
- Dubbo 接口调用结果缓存的实现分析
- maven的pom.xml文件错误Missing artifact org.springframework:spring-text:jar:4.1.7.RELEASE
- 幸运号码
- 资源分配
- 在你的网站服务器配置https