kafka常见操作命令

573 阅读6分钟

基础环境

zookeeper            3.4             b1d430ffe1a7   3 months ago   260MB
wurstmeister/kafka   2.11-0.10.2.2   ec06cc1b2422   6 months ago   408MB

kafka-topices.sh脚本命令参数

1、命令

--zookeeper : 指定了Kafka所连接的ZooKeeper服务地址
--topic : 指定了所要创建主题的名称
--replication-factor : 指定了副本因子
--partitions : 指定了分区个数
--create : 是创建主题的动作指令。

Command must include exactly one action: --list, --describe, --create, --alter or --delete
Option                                   Description
------                                   -----------
--alter                                  Alter the number of partitions,
                                           replica assignment, and/or
                                           configuration for the topic.
--config <String: name=value>            A topic configuration override for the
                                           topic being created or altered.The
                                           following is a list of valid
                                           configurations:
                                         	cleanup.policy
                                         	compression.type
                                         	delete.retention.ms
                                         	file.delete.delay.ms
                                         	flush.messages
                                         	flush.ms
                                         	follower.replication.throttled.
                                           replicas
                                         	index.interval.bytes
                                         	leader.replication.throttled.replicas
                                         	max.message.bytes
                                         	message.format.version
                                         	message.timestamp.difference.max.ms
                                         	message.timestamp.type
                                         	min.cleanable.dirty.ratio
                                         	min.compaction.lag.ms
                                         	min.insync.replicas
                                         	preallocate
                                         	retention.bytes
                                         	retention.ms
                                         	segment.bytes
                                         	segment.index.bytes
                                         	segment.jitter.ms
                                         	segment.ms
                                         	unclean.leader.election.enable
                                         See the Kafka documentation for full
                                           details on the topic configs.
--create                                 Create a new topic.
--delete                                 Delete a topic
--delete-config <String: name>           A topic configuration override to be
                                           removed for an existing topic (see
                                           the list of configurations under the
                                           --config option).
--describe                               List details for the given topics.
--disable-rack-aware                     Disable rack aware replica assignment
--force                                  Suppress console prompts
--help                                   Print usage information.
--if-exists                              if set when altering or deleting
                                           topics, the action will only execute
                                           if the topic exists
--if-not-exists                          if set when creating topics, the
                                           action will only execute if the
                                           topic does not already exist
--list                                   List all available topics.
--partitions <Integer: # of partitions>  The number of partitions for the topic
                                           being created or altered (WARNING:
                                           If partitions are increased for a
                                           topic that has a key, the partition
                                           logic or ordering of the messages
                                           will be affected
--replica-assignment <String:            A list of manual partition-to-broker
  broker_id_for_part1_replica1 :           assignments for the topic being
  broker_id_for_part1_replica2 ,           created or altered.
  broker_id_for_part2_replica1 :
  broker_id_for_part2_replica2 , ...>
--replication-factor <Integer:           The replication factor for each
  replication factor>                      partition in the topic being created.
--topic <String: topic>                  The topic to be create, alter or
                                           describe. Can also accept a regular
                                           expression except for --create option
--topics-with-overrides                  if set when describing topics, only
                                           show topics that have overridden
                                           configs
--unavailable-partitions                 if set when describing topics, only
                                           show partitions whose leader is not
                                           available
--under-replicated-partitions            if set when describing topics, only
                                           show under replicated partitions
--zookeeper <String: urls>               REQUIRED: The connection string for
                                           the zookeeper connection in the form
                                           host:port. Multiple URLS can be
                                           given to allow fail-over.

2、创建主题

./kafka-topics.sh --zookeeper 192.168.124.28:2181/kafka --create --topic topic-demo --replication-factor 1 --partitions 1

通过--replica-assignment创建

bash-4.4# /opt/kafka/bin/kafka-topics.sh --zookeeper 192.168.124.60:2181/kafka --create --topic topic-create-same --replica-assignment 3:1,1:2,2:3,3:2
Created topic "topic-create-same".
bash-4.4# /opt/kafka/bin/kafka-topics.sh --zookeeper 192.168.124.60:2181/kafka --describe --topic topic-create-same
Topic:topic-create-same	PartitionCount:4	ReplicationFactor:2	Configs:
	Topic: topic-create-same	Partition: 0	Leader: 3	Replicas: 3,1	Isr: 3,1
	Topic: topic-create-same	Partition: 1	Leader: 1	Replicas: 1,2	Isr: 1,2
	Topic: topic-create-same	Partition: 2	Leader: 2	Replicas: 2,3	Isr: 2,3
	Topic: topic-create-same	Partition: 3	Leader: 3	Replicas: 3,2	Isr: 3,2

3、展示所有主题 --list

bash-4.4# ./kafka-topics.sh  -zookeeper 192.168.124.60:2181/kafka --list
__consumer_offsets
sun
topic-create
topic-create-same
topic-demo
topic-study

4、展示主题的具体信息 --describe

--describe展示主题的更多具体信息

bash-4.4# ./kafka-topics.sh --zookeeper 192.168.124.28:2181/kafka --describe --topic topic-demo
Topic:topic-demo	PartitionCount:1	ReplicationFactor:1	Configs:
	Topic: topic-demo	Partition: 0	Leader: 0	Replicas: 0	Isr: 0

kafka-configs.sh脚本

Add/Remove entity config for a topic, client, user or broker
Option                      Description
------                      -----------
--add-config <String>       Key Value pairs of configs to add. Square brackets
                              can be used to group values which contain commas:
                              'k1=v1,k2=[v1,v2,v2],k3=v3'. The following is a
                              list of valid configurations: For entity_type
                              'topics':
                            	cleanup.policy
                            	compression.type
                            	delete.retention.ms
                            	file.delete.delay.ms
                            	flush.messages
                            	flush.ms
                            	follower.replication.throttled.replicas
                            	index.interval.bytes
                            	leader.replication.throttled.replicas
                            	max.message.bytes
                            	message.format.version
                            	message.timestamp.difference.max.ms
                            	message.timestamp.type
                            	min.cleanable.dirty.ratio
                            	min.compaction.lag.ms
                            	min.insync.replicas
                            	preallocate
                            	retention.bytes
                            	retention.ms
                            	segment.bytes
                            	segment.index.bytes
                            	segment.jitter.ms
                            	segment.ms
                            	unclean.leader.election.enable
                            For entity_type 'brokers':
                            	follower.replication.throttled.rate
                            	leader.replication.throttled.rate
                            For entity_type 'users':
                            	producer_byte_rate
                            	SCRAM-SHA-256
                            	SCRAM-SHA-512
                            	consumer_byte_rate
                            For entity_type 'clients':
                            	producer_byte_rate
                            	consumer_byte_rate
                            Entity types 'users' and 'clients' may be specified
                              together to update config for clients of a
                              specific user.
--alter                     Alter the configuration for the entity.
--delete-config <String>    config keys to remove 'k1,k2'
--describe                  List configs for the given entity.
--entity-default            Default entity name for clients/users (applies to
                              corresponding entity type in command line)
--entity-name <String>      Name of entity (topic name/client id/user principal
                              name/broker id)
--entity-type <String>      Type of entity (topics/clients/users/brokers)
--force                     Suppress console prompts
--help                      Print usage information.
--zookeeper <String: urls>  REQUIRED: The connection string for the zookeeper
                              connection in the form host:port. Multiple URLS
                              can be given to allow fail-over.

1、配置brokers下复制限流

./kafka-configs.sh --zookeeper 192.168.124.60:2181/kafka --entity-type brokers --entity-name 1 --alter --add-config follower.replication.throttled.rate=1024,leader.replication.throttled.rate=1024

2、删除配置

./kafka-configs.sh --zookeeper 192.168.124.60:2181/kafka --entity-type brokers --entity-name 1 --alter --delete-config follower.replication.throttled.rate,leader.replication.throttled.rate

3、配置主题级别复制限流

./kafka-configs.sh --zookeeper 192.168.124.60:2181/kafka --entity-type topics --entity-name topic-throttle  --alter --add-config follower.replication.throttled.replicas=[0:2,1:3,2:1],leader.replication.throttled.replicas=[0:1,1:2,2:3]

kafka-console-consumer.sh脚本

The console consumer is a tool that reads data from Kafka and outputs it to standard output.
Option                                   Description
------                                   -----------
--blacklist <String: blacklist>          Blacklist of topics to exclude from
                                           consumption.
--bootstrap-server <String: server to    REQUIRED (unless old consumer is
  connect to>                              used): The server to connect to.
--consumer-property <String:             A mechanism to pass user-defined
  consumer_prop>                           properties in the form key=value to
                                           the consumer.
--consumer.config <String: config file>  Consumer config properties file. Note
                                           that [consumer-property] takes
                                           precedence over this config.
--csv-reporter-enabled                   If set, the CSV metrics reporter will
                                           be enabled
--delete-consumer-offsets                If specified, the consumer path in
                                           zookeeper is deleted when starting up
--enable-systest-events                  Log lifecycle events of the consumer
                                           in addition to logging consumed
                                           messages. (This is specific for
                                           system tests.)
--formatter <String: class>              The name of a class to use for
                                           formatting kafka messages for
                                           display. (default: kafka.tools.
                                           DefaultMessageFormatter)
--from-beginning                         If the consumer does not already have
                                           an established offset to consume
                                           from, start with the earliest
                                           message present in the log rather
                                           than the latest message.
--key-deserializer <String:
  deserializer for key>
--max-messages <Integer: num_messages>   The maximum number of messages to
                                           consume before exiting. If not set,
                                           consumption is continual.
--metrics-dir <String: metrics           If csv-reporter-enable is set, and
  directory>                               this parameter isset, the csv
                                           metrics will be outputed here
--new-consumer                           Use the new consumer implementation.
                                           This is the default.
--offset <String: consume offset>        The offset id to consume from (a non-
                                           negative number), or 'earliest'
                                           which means from beginning, or
                                           'latest' which means from end
                                           (default: latest)
--partition <Integer: partition>         The partition to consume from.
--property <String: prop>                The properties to initialize the
                                           message formatter.
--skip-message-on-error                  If there is an error when processing a
                                           message, skip it instead of halt.
--timeout-ms <Integer: timeout_ms>       If specified, exit if no message is
                                           available for consumption for the
                                           specified interval.
--topic <String: topic>                  The topic id to consume on.
--value-deserializer <String:
  deserializer for values>
--whitelist <String: whitelist>          Whitelist of topics to include for
                                           consumption.
--zookeeper <String: urls>               REQUIRED (only when using old
                                           consumer): The connection string for
                                           the zookeeper connection in the form
                                           host:port. Multiple URLS can be
                                           given to allow fail-over.

1、订阅消息

bash-4.4# ./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic topic-demo --from-beginning
ouyangjun

2、创建消费组命令

./kafka-console-consumer.sh  --bootstrap-server 192.168.124.28:9092 --topic topic-study --consumer-property group.id=consumer_topic-study

kafka-console-producer.sh脚本

Read data from standard input and publish it to Kafka.
Option                                   Description
------                                   -----------
--batch-size <Integer: size>             Number of messages to send in a single
                                           batch if they are not being sent
                                           synchronously. (default: 200)
--broker-list <String: broker-list>      REQUIRED: The broker list string in
                                           the form HOST1:PORT1,HOST2:PORT2.
--compression-codec [String:             The compression codec: either 'none',
  compression-codec]                       'gzip', 'snappy', or 'lz4'.If
                                           specified without value, then it
                                           defaults to 'gzip'
--key-serializer <String:                The class name of the message encoder
  encoder_class>                           implementation to use for
                                           serializing keys. (default: kafka.
                                           serializer.DefaultEncoder)
--line-reader <String: reader_class>     The class name of the class to use for
                                           reading lines from standard in. By
                                           default each line is read as a
                                           separate message. (default: kafka.
                                           tools.
                                           ConsoleProducer$LineMessageReader)
--max-block-ms <Long: max block on       The max time that the producer will
  send>                                    block for during a send request
                                           (default: 60000)
--max-memory-bytes <Long: total memory   The total memory used by the producer
  in bytes>                                to buffer records waiting to be sent
                                           to the server. (default: 33554432)
--max-partition-memory-bytes <Long:      The buffer size allocated for a
  memory in bytes per partition>           partition. When records are received
                                           which are smaller than this size the
                                           producer will attempt to
                                           optimistically group them together
                                           until this size is reached.
                                           (default: 16384)
--message-send-max-retries <Integer>     Brokers can fail receiving the message
                                           for multiple reasons, and being
                                           unavailable transiently is just one
                                           of them. This property specifies the
                                           number of retires before the
                                           producer give up and drop this
                                           message. (default: 3)
--metadata-expiry-ms <Long: metadata     The period of time in milliseconds
  expiration interval>                     after which we force a refresh of
                                           metadata even if we haven't seen any
                                           leadership changes. (default: 300000)
--old-producer                           Use the old producer implementation.
--producer-property <String:             A mechanism to pass user-defined
  producer_prop>                           properties in the form key=value to
                                           the producer.
--producer.config <String: config file>  Producer config properties file. Note
                                           that [producer-property] takes
                                           precedence over this config.
--property <String: prop>                A mechanism to pass user-defined
                                           properties in the form key=value to
                                           the message reader. This allows
                                           custom configuration for a user-
                                           defined message reader.
--queue-enqueuetimeout-ms <Integer:      Timeout for event enqueue (default:
  queue enqueuetimeout ms>                 2147483647)
--queue-size <Integer: queue_size>       If set and the producer is running in
                                           asynchronous mode, this gives the
                                           maximum amount of  messages will
                                           queue awaiting sufficient batch
                                           size. (default: 10000)
--request-required-acks <String:         The required acks of the producer
  request required acks>                   requests (default: 1)
--request-timeout-ms <Integer: request   The ack timeout of the producer
  timeout ms>                              requests. Value must be non-negative
                                           and non-zero (default: 1500)
--retry-backoff-ms <Integer>             Before each retry, the producer
                                           refreshes the metadata of relevant
                                           topics. Since leader election takes
                                           a bit of time, this property
                                           specifies the amount of time that
                                           the producer waits before refreshing
                                           the metadata. (default: 100)
--socket-buffer-size <Integer: size>     The size of the tcp RECV size.
                                           (default: 102400)
--sync                                   If set message send requests to the
                                           brokers are synchronously, one at a
                                           time as they arrive.
--timeout <Integer: timeout_ms>          If set and the producer is running in
                                           asynchronous mode, this gives the
                                           maximum amount of time a message
                                           will queue awaiting sufficient batch
                                           size. The value is given in ms.
                                           (default: 1000)
--topic <String: topic>                  REQUIRED: The topic id to produce
                                           messages to.
--value-serializer <String:              The class name of the message encoder
  encoder_class>                           implementation to use for
                                           serializing values. (default: kafka.
                                           serializer.DefaultEncoder)

1、生产消息

bash-4.4# ./kafka-console-producer.sh --broker-list localhost:9092 --topic topic-demo
ouyangjun

kafka-producer-perf-test.sh脚本

生产者性能测试工具

optional arguments:
  -h, --help             show this help message and exit
  --topic TOPIC          produce messages to this topic
  --num-records NUM-RECORDS
                         number of messages to produce
  --payload-delimiter PAYLOAD-DELIMITER
                         provides delimiter to be used when --payload-file is provided. Defaults to new line. Note that this parameter will be ignored if --payload-file is not provided. (default: \n)
  --throughput THROUGHPUT
                         throttle maximum message throughput to *approximately* THROUGHPUT messages/sec
  --producer-props PROP-NAME=PROP-VALUE [PROP-NAME=PROP-VALUE ...]
                         kafka producer related configuration properties like bootstrap.servers,client.id etc. These configs take precedence over those passed via --producer.config.
  --producer.config CONFIG-FILE
                         producer config properties file.

  either --record-size or --payload-file must be specified but not both.

  --record-size RECORD-SIZE
                         message size in bytes. Note that you must provide exactly one of --record-size or --payload-file.
  --payload-file PAYLOAD-FILE
                         file to read the message payloads from. This works only for UTF-8  encoded  text  files.  Payloads  will  be  read from this file and a payload will be randomly selected when
                         sending messages. Note that you must provide exactly one of --record-size or --payload-file.

参考

kafka
kafka实操(创建主题,生产者,消费者组,查看消费偏移,删除主题)