kafka和springboot整合应用
加载依赖
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
yml对应配置
spring:
kafka:
bootstrap-servers: sjck-node03:9092,sjck-node03:9093,sjck-node03:9094
consumer:
group-id: single-consumer-group
生产者
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class KafkaProducer {
@Autowired
private KafkaTemplate kafkaTemplate;
@RequestMapping("/send")
public String send(String name){
kafkaTemplate.send("kafka-action",name);
return name;
}
}
消费者
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class KafkaConsumer {
@KafkaListener(topics = "kafka-action")
public void listen(ConsumerRecord<?,String> record){
String value = record.value();
System.out.println(value);
System.out.println(record.toString());
}
}
springboot项目启动成功,会打印出producer和consumer相关的配置信息
producer请求send接口
http://localhost:8011/send?name=today
today
控制台consumer输出
2019-03-17 18:05:41.155 INFO 84622 --- [nio-8011-exec-1] o.a.kafka.common.utils.AppInfoParser : Kafka version : 0.10.1.1
2019-03-17 18:05:41.155 INFO 84622 --- [nio-8011-exec-1] o.a.kafka.common.utils.AppInfoParser : Kafka commitId : f10ef2720b03b247
today
ConsumerRecord(topic = kafka-action, partition = 0, offset = 8, CreateTime = 1552817141215, checksum = 435080069, serialized key size = -1, serialized value size = 5, key = null, value = today)
posted on 2019-03-24 19:45 OneLi算法分享社区 阅读(152) 评论(0) 编辑 收藏 举报