Kafka生产者消费者实例

本文介绍了一个简单的Kafka消费者和生产者的实现案例。消费者从指定主题接收消息并打印出来,而生产者则不断从队列中获取消息并发送到指定的主题。文章通过具体的Java代码展示了如何加载配置信息,并利用这些配置来创建消费者和生产者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要实现Kafka消费者和生产者最基础功能。

消费者实例:

public class MyKafkaConsumer implements Runnable {
private String topic;
public MyKafkaConsumer(String topic) {
super();
this.topic = topic;
}
// 加載kafka配置信息
public Properties createKafkaProperties() {
InputStream in = MyKafkaConsumer.class.getResourceAsStream("/kafka.properties");
Properties prop = new Properties();
try {
prop.load(in);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return prop;
}
@Override
public void run() {
// 獲取kafka連接
ConsumerConnector consumer = Consumer.createJavaConsumerConnector(new ConsumerConfig(createKafkaProperties()));
Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
topicCountMap.put(topic, 1);
Map<String,List<KafkaStream<byte[],byte[]>>> messageStreams = consumer.createMessageStreams(topicCountMap);
KafkaStream<byte[],byte[]> stream = messageStreams.get(topic).get(0);
ConsumerIterator<byte[],byte[]> iterator = stream.iterator();
while(iterator.hasNext()) {
String message = new String(iterator.next().message());
System.out.println("接收到: " + message);
}

}
public static void main(String[] args) {
new Thread(new MyKafkaConsumer("test")).start();
}
}

生产者实例:

public class MyKafkaProducer implements Runnable {
private String topic;
private LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
public MyKafkaProducer(String topic,LinkedBlockingQueue<String> queue) {
super();
this.topic = topic;
this.queue = queue;
}
public Properties createProperties() {
InputStream in = MyKafkaProducer.class.getResourceAsStream("/kafkaProducer");
Properties prop = new Properties();
try {
prop.load(in);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return prop;
}

@Override
public void run() {
Producer<String, String> producer = new Producer<>(new ProducerConfig(createProperties()));

while(true) {

try {

//此处可以为发送的消息指定Key和Value,进而能够根据指定key进行相应分区

producer.send(new KeyedMessage<String, String>(topic, queue.take()));
} catch (InterruptedException e) {
e.printStackTrace();
}

}

}

}


注:添加prop.put("serializer.class", StringEncoder.class.getName());语句,否则报序列化错误




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值