1、按分区消费
application.properties:
#主题
msg.kafka.topic=kafkatopic
@Component
public class KafkaController {
@KafkaListener(id = "0",topicPartitions = {@TopicPartition(topic ="${msg.kafka.topic}",partitions = {"0"})})
public void listenPartition0(String records)throws Exception{
//System.out.println(records);
}
@KafkaListener(id = "1",topicPartitions = {@TopicPartition(topic ="${msg.kafka.topic}",partitions = {"1"})})
public void listenPartition1(String records)throws Exception{
//System.out.println(records);
}
@KafkaListener(id = "2",topicPartitions = {@TopicPartition(topic ="${msg.kafka.topic}",partitions = {"2"})})
public void listenPartition2(String records)throws Exception{
//System.out.println(records);
}
}
2、按主题消费
@Component
public class FraudCheckConsumerListener {
@KafkaListener(topics = "${spring.kafka.consumer.topic}", groupId = "${spring.kafka.comsumer.group-id}")
public void listener(String record) throws Exception{
System.out.println("消息:"+record);
}
}
3、定时向主题发送消息
定时类:
@Component
public class ScheduledService {
@Autowired
private KafkaTemplate kafkaTemplate;
Logger logger= LoggerFactory.getLogger(ScheduledHService.class);
@Scheduled(cron = "0/6 * * * * *")
@Async
public void test()throws Exception {
kafkaTemplate.send("要发送的消息");
}
}