启动kafka
bin/kafka-server-start.sh -daemon config/server.properties
创建消费者
bin/kafka-console-consumer.sh --bootstrap-server 192.168.142.100:9092 --from-beginning --topic newTopic
创建生产者
bin/kafka-console-producer.sh --broker-list 192.168.142.100:9092 --topic newTopic
使用flume监控文件并输出到kafka
1. 配置文件 flume2kafka.conf
#定义了当前agent的名字叫做a1
a1.sources = r1
a1.sinks = k1
a1.channels = c1
# Describe/configure the source
a1.sources.r1.type = exec
a1.sources.r1.command = tail -F /root/log/log.txt
a1.sources.r1.shell=/bin/sh -c
# Describe the sink
a1.sinks.k1.type = logger
# Use a channel which buffers events in memory
a1.channels.c1.type = memory
a1.channels.c1.capacity = 1000
a1.channels.c1.transactionCapacity = 100
# Bind the source and sink to the channel
a1.sources.r1.channels = c1
a1.sinks.k1.channel = c1
# 指定Flume sink
#a1.sinks.k1.type = logger
a1.sinks.k1.type = org.apache.flume.sink.kafka.KafkaSink
a1.sinks.k1.topic = aiqiyi
a1.sinks.k1.brokerList = 192.168.142.100:9092
a1.sinks.k1.requiredAcks = 1
a1.sinks.k1.batchSize = 100
2. 启动flume
bin/flume-ng agent -c conf -f conf/flume2kafka.conf --name a1 -Dflume.root.logger=INFO,console
3. 修改log.txt文件
4. 启动kafka消费
bin/kafka-console-consumer.sh --bootstrap-server 192.168.142.100:9092 --topic aiqiyi --from-beginning
IDEA scala代码
import java.util.Properties
import kafka.admin.{AdminUtils, RackAwareMode}
import kafka.consumer.{Consumer, ConsumerConfig}
import kafka.javaapi.producer.Producer
import kafka.producer.{KeyedMessage, ProducerConfig}
import kafka.utils.ZkUtils
import org.apache.kafka.common.security.JaasUtils
import collection.JavaConversions._
object test {
def main(args: Array[String]): Unit = {
testConsumer
}
def testConsumer {
val topic = "newTopic"
val props = new Properties()
props.put("zookeeper.connect", "192.168.142.100:2181,192.168.142.101:2181,192.168.142.102:2181")
props.put("group.id", "testGroup")
val consumerConnector = Consumer.createJavaConsumerConnector(new ConsumerConfig(props))
val topicCountMap = Map(topic -> new Integer(1))
val messageStreams = consumerConnector.createMessageStreams(topicCountMap)
val stream = messageStreams.get(topic).get(0)
val iterator = stream.iterator()
while (iterator.hasNext) {
val msg = new String(iterator.next.message)
println(msg)
}
}
}