Kafka原理图
JAVA源代码之kafka生产者,本次客户端使用kafka的console命令行,消费,生产者使用代码编码。看了好多生产者代码都带有props.put("zk.connect", "n2:2181/jafka"); 真是感到不解,没有这个参数也可以运行的好好的,实践出真知,弄懂原理真的很重要,具体如下:
import java.util.Properties;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
/**
* 0.7.2
* @author Administrator
*
*/
public class ProducerSample {
public static void main(String[] args) {
String topicName = "test";
String data = "this is a java-test. i Am gaojs";
ProducerSample ps = new ProducerSample();
Properties props = new Properties();
props.put("metadata.broker.list", "192.168.1.101:9092");
props.put("serializer.class", "kafka.serializer.StringEncoder");
props.put("request.required.acks","1");
ProducerConfig config = new ProducerConfig(props);
Producer<String, String> producer = new Producer<String, String>(config);
KeyedMessage<String, String> keyedMessage = new KeyedMessage<String, String>(topicName, data);
producer.send(keyedMessage);
producer.close();
}
}
MAVEN环境
<dependencies>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.10</artifactId>
<version>0.9.0.1</version>
<exclusions>
<exclusion>
<artifactId>jmxtools</artifactId>
<groupId>com.sun.jdmk</groupId>
</exclusion>
<exclusion>
<artifactId>jmxri</artifactId>
<groupId>com.sun.jmx</groupId>
</exclusion>
<exclusion>
<artifactId>jms</artifactId>
<groupId>javax.jms</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<artifactId>jmxtools</artifactId>
<groupId>com.sun.jdmk</groupId>
</exclusion>
<exclusion>
<artifactId>jmxri</artifactId>
<groupId>com.sun.jmx</groupId>
</exclusion>
<exclusion>
<artifactId>jms</artifactId>
<groupId>javax.jms</groupId>
</exclusion>
<exclusion>
<artifactId>mail</artifactId>
<groupId>javax.mail</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
实践截图
启动zk
创建topic
消费消息