MAPREDUCE服务 MRS-使用SpringBoot生产消费Kafka集群数据:代码样例

时间:2024-07-29 08:59:49

代码样例

通过SpringBoot实现Kafka生产消费的样例代码如下:

@RestController
public class MessageController {
    private final static Logger  LOG  = LoggerFactory.getLogger(MessageController.class);
    @Autowired
    private KafkaProperties kafkaProperties;
    @GetMapping("/produce")
    public String produce() {
        Producer producerThread = new Producer();
        producerThread.init(this.kafkaProperties);
        producerThread.start();
        String message = "Start to produce messages";
        LOG.info(message);
        return message;
    }
    @GetMapping("/consume")
    public String consume() {
        Consumer consumerThread = new Consumer();
        consumerThread.init(this.kafkaProperties);
        consumerThread.start();
        LOG.info("Start to consume messages");
        // 等到180s后将consumer关闭,实际执行过程中可修改
        try {
            Thread.sleep(consumerThread.getThreadAliveTime());
        } catch (InterruptedException e) {
            LOG.info("Occurred InterruptedException: ", e);
        } finally {
            consumerThread.close();
        }
        return String.format("Finished consume messages");
    }
}
support.huaweicloud.com/devg-lts-mrs/mrs_07_130039.html