0%

SpringBoot集成Kafka

pom.xml

1
2
3
4
5
<!-- kafka -->
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>

application.yml

1
2
3
4
5
spring:
kafka:
bootstrap-servers: 192.168.3.206:9002
consumer:
group-id: mygroup

提供者

1
2
3
4
5
6
7
8
9
10
11
12
@RunWith(SpringRunner.class)
@SpringBootTest
public class KafkaTest {
@Resource
private KafkaTemplate kafkaTemplate;

@Test
public void providerTest() {
kafkaTemplate.send("myTopic", "Test Message!");
}

}

消费者

1
2
3
4
5
6
7
8
9
10
11
@Component
@Slf4j
public class KafkaConsumer {

@KafkaListener(topics = "myTopic")
public void listen(ConsumerRecord<?, String> record) {
String value = record.value();
log.info(value);
log.info(JSON.toJSONString(record));
}
}