spring kafka简单应用

(1)依赖

build.gradle

compile('org.springframework.kafka:spring-kafka')

(2)配置

application.properties

spring.kafka.bootstrap-servers=localhost:9093
spring.kafka.consumer.group-id=test

(3)生产者

@Autowired
private KafkaTemplate<String, Object> kafkaTemplate;

@RequestMapping(value = "f1", method = RequestMethod.GET)
public void f1(@RequestParam(required = true) String data) {
	kafkaTemplate.send("test", data);
}

@RequestMapping(value = "f2", method = RequestMethod.GET)
public void f2(@RequestParam(required = true) String data) {
	kafkaTemplate.send("test", data).addCallback(new SuccessCallback<SendResult<String, Object>>() {

		@Override
		public void onSuccess(SendResult<String, Object> result) {
			String topic = result.getRecordMetadata().topic();
			int partition = result.getRecordMetadata().partition();
			long offset = result.getRecordMetadata().offset();
			log.info("{}:{}:{}", topic, partition, offset);
		}
		
	}, new FailureCallback() {

		@Override
		public void onFailure(Throwable ex) {
			log.error("{}", ex.getMessage());
		}
		
	});
}

@RequestMapping(value = "f3", method = RequestMethod.GET)
public void f3(@RequestParam(required = true) String data) {
	kafkaTemplate.send("test", data).addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {

		@Override
		public void onSuccess(SendResult<String, Object> result) {
			String topic = result.getRecordMetadata().topic();
			int partition = result.getRecordMetadata().partition();
			long offset = result.getRecordMetadata().offset();
			log.info("{}:{}:{}", topic, partition, offset);
		}

		@Override
		public void onFailure(Throwable ex) {
			log.error("{}", ex.getMessage());
		}
		
	});
}

(4)消费者

@KafkaListener(topics = {"test"})
public void f4(ConsumerRecord<String, Object> record) {
	log.info("{}:{}:{}:{}:{}:{}", record.topic(), record.partition(), record.key(), record.value(), record.offset(), record.timestamp());
}

(5)测试结果

2024-04-19 15:10:55 [org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] INFO  cn.hwd.controller.Test3Controller - test:0:null:hello:21:1713510655274 
2024-04-19 15:10:59 [kafka-producer-network-thread | producer-1] INFO  cn.hwd.controller.Test3Controller - test:0:22 
2024-04-19 15:10:59 [org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] INFO  cn.hwd.controller.Test3Controller - test:0:null:hello:22:1713510659344 
2024-04-19 15:11:04 [kafka-producer-network-thread | producer-1] INFO  cn.hwd.controller.Test3Controller - test:0:23 
2024-04-19 15:11:04 [org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] INFO  cn.hwd.controller.Test3Controller - test:0:null:hello:23:1713510664393 
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值