一、依赖
<dependency>
<groupId>org.springframework.kafkagroupId>
<artifactId>spring-kafkaartifactId>
<version>2.5.1.RELEASEversion>
dependency>
二、配置文件
spring:
kafka:
bootstrap-servers: localhost:9092
consumer:
group-id: testGroup
auto-offset-reset: latest
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
三、API
1、生产者
@Component
public class ProducerMsg {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void send(String topic, String msg) {
kafkaTemplate.send(topic, msg);
}
public void sendCallback(String topic, String msg) {
kafkaTemplate.send(topic, msg).addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
@Override
public void onSuccess(SendResult<String, String> stringStringSendResult) {
RecordMetadata recordMetadata = stringStringSendResult.getRecordMetadata();
final String topic = recordMetadata.topic();
final int partition = recordMetadata.partition();
final long offset = recordMetadata.offset();
System.err.println(String.format("生产消息成功:topic: %s,partition: %s,offset: %s", topic, partition, offset));
}
@Override
public void onFailure(Throwable throwable) {
}
});
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
2、消费者
@Component
public class ConsumeMsg {
@KafkaListener(topics = {"USER", "LOG"})
public void consumeSingle(ConsumerRecord<String, String> consumer) {
System.err.println("监听到kafka消息: " + consumer);
final String topic = consumer.topic();
final String value = consumer.value();
}
public void consumeBatch(List<ConsumerRecord<String, String>> consumers) {
consumers.forEach(consumer -> {
final String topic = consumer.topic();
final String value = consumer.value();
System.err.println(String.format("topic: %s,value: %s", topic, value));
});
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38