转载自五四陈科学院[http://www.54chen.com]
本文链接: http://www.54chen.com/java-ee/linkedin-kafka-usage.html
kafka是一种高吞吐量的分布式发布订阅消息系统,她有如下特性:
设计侧重高吞吐量,用于好友动态,相关性统计,排行统计,访问频率控制,批处理等系统。大部分的消息中间件能够处理实时性要求高的消息/数据,但是对于队列中大量未处理的消息/数据在持久性方面比较弱。
kakfa的consumer使用拉的方式工作。
安装kafka
下载:http://people.apache.org/~nehanarkhede/kafka-0.7.0-incubating/kafka-0.7.0-incubating-src.tar.gz
> tar xzf kafka-.tgz
> cd kafka-
> ./sbt update
> ./sbt package
启动zkserver:
bin/zookeeper-server-start.sh config/zookeeper.properties
启动server:
bin/kafka-server-start.sh config/server.properties
就是这么简单。
使用kafka
- import java.util.Arrays;
- import java.util.List;
- import java.util.Properties;
- import kafka.javaapi.producer.SyncProducer;
- import kafka.javaapi.message.ByteBufferMessageSet;
- import kafka.message.Message;
- import kafka.producer.SyncProducerConfig;
- ...
- Properties props = new Properties();
- props.put(“zk.connect”, “127.0.0.1:2181”);
- props.put("serializer.class", "kafka.serializer.StringEncoder");
- ProducerConfig config = new ProducerConfig(props);
- Producer producer = new Producer(config);
- Send a single message
- // The message is sent to a randomly selected partition registered in ZK
- ProducerData data = new ProducerData("test-topic", "test-message");
- producer.send(data);
- producer.close();
这样就是一个标准的producer。
consumer的代码
- // specify some consumer properties
- Properties props = new Properties();
- props.put("zk.connect", "localhost:2181");
- props.put("zk.connectiontimeout.ms", "1000000");
- props.put("groupid", "test_group");
- // Create the connection to the cluster
- ConsumerConfig consumerConfig = new ConsumerConfig(props);
- ConsumerConnector consumerConnector = Consumer.createJavaConsumerConnector(consumerConfig);
- // create 4 partitions of the stream for topic “test”, to allow 4 threads to consume
- Map>> topicMessageStreams =
- consumerConnector.createMessageStreams(ImmutableMap.of("test", 4));
- List> streams = topicMessageStreams.get("test");
- // create list of 4 threads to consume from each of the partitions
- ExecutorService executor = Executors.newFixedThreadPool(4);
- // consume the messages in the threads
- for(final KafkaMessageStream stream: streams) {
- executor.submit(new Runnable() {
- public void run() {
- for(Message message: stream) {
- // process message
- }
- }
- });
- }
原创文章如转载,请注明:转载自五四陈科学院[http://www.54chen.com]