1、依赖jar包
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>0.10.2.1</version>
</dependency>
至少需要2个jar
2、生产者
public class SendMessageProducer {
public static final String SERVERS = "10.238.103.140:9095";
public static final String TOPIC = "mldn-topic";
public static void main(String[] args) {
// 如果要想进行Kafka消息发送需要使用Properties定义一些环境属性
Properties props = new Properties();
props.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, SERVERS); // 定义Kafka服务地址
// Kafka之中是以key和value的形式进行消息的发送处理, 所以为了保证Kafka的性能,专门提供有统一类型
// props.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer") ;
props.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()) ;
props.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()) ;
long start = System.currentTimeMillis() ;
// 定义消息发送者对象,依靠此对象可以进行消息的传递
Producer<String,String> producer = new KafkaProducer<String,String>(props) ;
for (int x = 0 ; x < 1 ; x ++) {
producer.send(new ProducerRecord<String,String>(TOPIC,"mldn-" + x,"mldn-" +x)) ;
}
long end = System.currentTimeMillis() ;
System.out.println("*** 消息发送完成:" + (end - start));
producer.close();
}
}
3、消费者
public class ReceiveMessageConsumer {
public static final String SERVERS = "10.238.103.140:9095";
public static final String TOPIC = "mldn-topic";
public static void main(String[] args) {
Properties props = new Properties() ;
// 定义消息消费者的连接服务器地址
props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, SERVERS) ;
// 消息消费者一定要设置反序列化的程序类,与消息生产者完全对应
props.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()) ;
props.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()) ;
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "group-1") ;
// 定义消费者处理对象
Consumer<String,String> consumer = new KafkaConsumer<String,String>(props) ;
consumer.subscribe(Arrays.asList(TOPIC)); // 设置消费者读取的主题名称
boolean flag = true ; // 消费者需要一直进行数据的读取处理操作
while (flag) { // 一直读取消息
ConsumerRecords<String, String> allRecorders = consumer.poll(200) ;
for (ConsumerRecord<String, String> record : allRecorders) {
System.out.println("key = " + record.key() + "、value = " + record.value());
}
}
consumer.close();
}
}
4、消费队列与订阅
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "group-1") ;
如果设置的组消费者的消费组相同,表示属于队列消息,队列消息可以容纳的消费者是分区数量,分区和服务器的核数有关
如果设置费者的消费组不同,则表示主题订阅消息,那么订阅者可以有无数个,所有的消费者将取得各自的全部内容