PageRenderTime 327ms CodeModel.GetById 30ms RepoModel.GetById 2ms app.codeStats 0ms

/kafka/quickstart.php

https://github.com/mitultiwari/sna-page
PHP | 232 lines | 178 code | 48 blank | 6 comment | 8 complexity | 61112d1f3f1efb8bf460897210ab2b30 MD5 | raw file
  1. <?php require "includes/project_info.php" ?>
  2. <?php require "../includes/header.php" ?>
  3. <?php include "../includes/advert.php" ?>
  4. <h2>Quick Start</h3>
  5. <h3> Step 1: Download the code </h3>
  6. <a href="downloads" title="Kafka downloads">Download</a> a recent stable release.
  7. <pre>
  8. <b>&gt; tar xzf kafka-&lt;VERSION&gt;.tgz</b>
  9. <b>&gt; cd kafka-&lt;VERSION&gt;</b>
  10. </pre>
  11. <h3>Step 2: Start the server</h3>
  12. Kafka brokers and consumers use this for co-ordination.
  13. <p>
  14. First start the zookeeper server. You can use the convenience script packaged with kafka to get a quick-and-dirty single-node zookeeper instance.
  15. <pre>
  16. <b>&gt; bin/zookeeper-server-start.sh config/zookeeper.properties</b>
  17. [2010-11-21 23:45:02,335] INFO Reading configuration from: config/zookeeper.properties
  18. ...
  19. </pre>
  20. Now start the Kafka server:
  21. <pre>
  22. <b>&gt; bin/kafka-server-start.sh config/server.properties</b>
  23. jkreps-mn-2:kafka-trunk jkreps$ bin/kafka-server-start.sh config/server.properties
  24. [2010-11-21 23:51:39,608] INFO starting log cleaner every 60000 ms (kafka.log.LogManager)
  25. [2010-11-21 23:51:39,628] INFO connecting to ZK: localhost:2181 (kafka.server.KafkaZooKeeper)
  26. ...
  27. </pre>
  28. <h3>Step 3: Send some messages</h3>
  29. A toy producer script is available to send plain text messages. To use it, run the following command:
  30. <pre>
  31. <b>&gt; bin/kafka-producer-shell.sh --server kafka://localhost:9092 --topic test</b>
  32. > hello
  33. sent: hello (14 bytes)
  34. > world
  35. sent: world (14 bytes)
  36. </pre>
  37. <h3>Step 5: Start a consumer</h3>
  38. Start a toy consumer to dump out the messages you sent to the console:
  39. <pre>
  40. <b>&gt; bin/kafka-consumer-shell.sh --topic test --props config/consumer.properties</b>
  41. Starting consumer...
  42. ...
  43. consumed: hello
  44. consumed: world
  45. </pre>
  46. If you have each of the above commands running in a different terminal then you should now be able to type messages into the producer terminal and see them appear in the consumer terminal.
  47. <h3>Step 6: Write some code</h3>
  48. Below is some very simple examples of using Kafka for sending messages, more complete examples can be found in the Kafka source code in the examples/ directory.
  49. <h4>Producer Code</h4>
  50. <h5>1. send() API </h5>
  51. Using the producer is quite simple:
  52. <pre>
  53. String host = "localhost";
  54. int port = 9092;
  55. int bufferSize = 64*1024;
  56. int connectionTimeoutMs = 30*1000;
  57. int reconnectInterval = 1000;
  58. SimpleProducer producer = new SimpleProducer(host, port, bufferSize, connectionTimeoutMs, reconnectInterval);
  59. String topic = "test";
  60. int partition = 0;
  61. List<Message> messages = Arrays.asList(new Message("a message".getBytes()),
  62. new Message("another message".getBytes()),
  63. new Message("a third message".getBytes()));
  64. producer.send(topic, partition, messages)
  65. </pre>
  66. <h5>2. Log4j appender </h5>
  67. Data can also be produced to a Kafka server in the form of a log4j appender. In this way, minimal code needs to be written in order to send some data across to the Kafka server.
  68. Here is an example of how to use the Kafka Log4j appender -
  69. Start by defining the Kafka appender in your log4j.properties file.
  70. <pre>
  71. <small>// define the kafka log4j appender config parameters</small>
  72. log4j.appender.KAFKA=kafka.log4j.KafkaAppender
  73. <small>// set the hostname of the kafka server</small>
  74. log4j.appender.KAFKA.Host=localhost
  75. <small>// set the port on which the Kafka server is listening for connections</small>
  76. log4j.appender.KAFKA.Port=9092
  77. <small>// the topic under which the logger messages are to be posted</small>
  78. log4j.appender.KAFKA.Topic=test-topic
  79. <small>// the serializer to be used to turn an object into a Kafka message</small>
  80. log4j.appender.KAFKA.Serializer=kafka.log4j.AppenderStringSerializer
  81. <small>// do not set the above KAFKA appender as the root appender</small>
  82. log4j.rootLogger=INFO
  83. <small>// set the logger for your package to be the KAFKA appender</small>
  84. log4j.logger.test.package=INFO, KAFKA
  85. </pre>
  86. Data can be sent using a log4j appender as follows -
  87. <pre>
  88. Logger logger = Logger.getLogger(classOf[KafkaLog4jAppenderTest])
  89. logger.info("test")
  90. </pre>
  91. <h5>3. Asynchronous batching producer </h5>
  92. This is a higher level producer API, providing tunable batching of messages and asynchronous dispatch of batches of serialized messages to the configured Kafka server.
  93. <p>The batching of data can be controlled using the following parameters -
  94. <ul>
  95. <li> queue size &ndash; this parameter specifies the total size of the in memory queue used by the batching producer. A batch cannot be larger than this value. </li>
  96. <li> batch size &ndash; this parameter specifies a batch of data buffered in the producer queue. Once more data than this size is accumulated, it is serialized and sent to the Kafka server. </li>
  97. <li> serializer class &ndash; this specifies the serializer to be used by the async producer to serialize the incoming data into sets of Kafka messages, before sending them to the Kafka server. </li>
  98. <li> queue time in ms &ndash; this parameter controls the time for which the batched data lives in the queue. Once this time expires, the data in the queue is serialized and dispatched to the Kafka server. </li>
  99. </ul>
  100. </p>
  101. Here is some code on how to use the asynchronous batching producer -
  102. <pre>
  103. Properties props = new Properties();
  104. props.put("host", "localhost");
  105. props.put("port", "9092");
  106. props.put("queue.size", "200");
  107. props.put("serializer.class", "kafka.producer.StringSerializer");
  108. ProducerConfig config = new ProducerConfig(props);
  109. SimpleProducer basicProducer = new SimpleProducer(host, port, 64*1024, 100000, 10000);
  110. AsyncKafkaProducer[String] producer = new AsyncKafkaProducer[String](config, basicProducer, new StringSerializer());
  111. <small>// start the async producer</small>
  112. producer.start();
  113. for(i <- 0 until 200) {
  114. producer.send("test");
  115. }
  116. producer.close();
  117. </pre>
  118. Here is a simple string serializer used by the above example -
  119. <pre>
  120. class StringSerializer extends Serializer<String> {
  121. public String toEvent(Message message) { return message.toString(); }
  122. public Message toMessage(String event) { return new Message(event.getBytes); }
  123. public getTopic(String event) { return event.concat("-topic"); }
  124. }
  125. </pre>
  126. <h4>Consumer Code</h4>
  127. The consumer code is slightly more complex as it enables multithreaded consumption:
  128. <pre>
  129. // specify some consumer properties
  130. Properties props = new Properties();
  131. props.put("zk.connect", "localhost:2181");
  132. props.put("zk.connectiontimeout.ms", "1000000");
  133. props.put("groupid", "test_group");
  134. // Create the connection to the cluster
  135. ConsumerConfig consumerConfig = new ConsumerConfig(props);
  136. ConsumerConnector consumerConnector = Consumer.create(consumerConfig);
  137. // create 4 partitions of the stream for topic “test”, to allow 4 threads to consume
  138. Map&lt;String, List&lt;KafkaMessageStream&gt;&gt; topicMessageStreams =
  139. consumerConnector.createMessageStreams(ImmutableMap.of("test", 4));
  140. List&lt;KafkaMessageStream&gt; streams = topicMessageStreams.get("test")
  141. // create list of 4 threads to consume from each of the partitions
  142. ExecutorService executor = Executors.newFixedThreadPool(4);
  143. // consume the messages in the threads
  144. for(final KafkaMessageStream>> stream: streams) {
  145. executors.submit(new Runnable() {
  146. public void run() {
  147. for(Message message: stream) {
  148. // process message
  149. }
  150. }
  151. });
  152. }
  153. </pre>
  154. <h4>Hadoop Consumer</h4>
  155. <p>
  156. Providing a horizontally scalable solution for aggregating and loading data into Hadoop was one of our basic use cases. To support this use case, we provide a Hadoop-based consumer which spawns off many map tasks to pull data from the Kafka cluster in parallel. This provides extremely fast pull-based Hadoop data load capabilities (we were able to fully saturate the network with only a handful of Kafka servers).
  157. </p>
  158. <p>
  159. Usage information on the hadoop consumer can be found <a href="https://github.com/kafka-dev/kafka/tree/master/contrib/hadoop-consumer">here</a>.
  160. </p>
  161. <h4>Simple Consumer</h4>
  162. Kafka has a lower-level consumer api for reading message chunks directly from servers. Under most circumstances this should not be needed. But just in case, it's usage is as follows:
  163. <pre>
  164. <small>// create a consumer to connect to the server host, port, socket timeout of 10 secs, socket receive buffer of ~1MB</small>
  165. SimpleConsumer consumer = new SimpleConsumer(host, port, 10000, 1024000);
  166. long offset = 0;
  167. while (true) {
  168. <small>// create a fetch request for topic “test”, partition 0, current offset, and fetch size of 1MB</small>
  169. FetchRequest fetchRequest = new FetchRequest("test", 0, offset, 1000000);
  170. <small>// get the message set from the consumer and print them out</small>
  171. ByteBufferMessageSet messages = consumer.fetch(fetchRequest);
  172. for(message : messages) {
  173. System.out.println("consumed: " + Utils.toString(message.payload, "UTF-8"))
  174. <small>// advance the offset after consuming each message</small>
  175. offset += MessageSet.entrySize(message);
  176. }
  177. }
  178. </pre>
  179. <?php require "../includes/footer.php" ?>