卡夫卡gradle

Spring Kafka 消息发送与消费详解
本文详细介绍了如何使用 Spring Kafka 发送和消费消息,包括配置 Gradle 依赖、理解主题、分区和消息位置的概念,以及使用 KafkaTemplate 类进行消息发送的源码解析。同时,展示了如何通过 @KafkaListener 注解实现消息消费。

可参考系列文章地址:https://www.jianshu.com/p/f5eaa32cf1f3

gradle依赖

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

概念:

主题(topic),分区,消息位置(offset,偏移量),关系:1:n:n

类:KafkaTemplate,ProducerRecord,ConsumerRecord

发送消息:源码

kafkaTemplate.send("c2", "shenke");
@Override
	public ListenableFuture<SendResult<K, V>> send(String topic, V data) {
		ProducerRecord<K, V> producerRecord = new ProducerRecord<>(topic, data);
		return doSend(producerRecord);
	}
protected ListenableFuture<SendResult<K, V>> doSend(final ProducerRecord<K, V> producerRecord) {
		getTheProducer();
		if (this.logger.isTraceEnabled()) {
			this.logger.trace("Sending: " + producerRecord);
		}
		final SettableListenableFuture<SendResult<K, V>> future = new SettableListenableFuture<>();
		getTheProducer().send(producerRecord, new Callback() {

			@Override
			public void onCompletion(RecordMetadata metadata, Exception exception) {
				if (exception == null) {
					future.set(new SendResult<>(producerRecord, metadata));
					if (KafkaTemplate.this.producerListener != null
							&& KafkaTemplate.this.producerListener.isInterestedInSuccess()) {
						KafkaTemplate.this.producerListener.onSuccess(producerRecord.topic(),
								producerRecord.partition(), producerRecord.key(), producerRecord.value(), metadata);
					}
				}
				else {
					future.setException(new KafkaProducerException(producerRecord, "Failed to send", exception));
					if (KafkaTemplate.this.producerListener != null) {
						KafkaTemplate.this.producerListener.onError(producerRecord.topic(),
								producerRecord.partition(), producerRecord.key(), producerRecord.value(), exception);
					}
				}
			}

		});
		if (this.autoFlush) {
			flush();
		}
		if (this.logger.isTraceEnabled()) {
			this.logger.trace("Sent: " + producerRecord);
		}
		return future;
	}

消费消息

//kafka消费消息
	@KafkaListener(topics ="c2")
	public void executeIptvTask(ConsumerRecord<?, ?> cr) {
		   ObjectMapper mapper = new ObjectMapper();
		   //KafkaConsumer<String, String> consumer = new KafkaConsumer<>(configs);
		try {
			// kafkaTemplate.send("c2", "shenke");
			IptvTask	iptvTask = mapper.readValue((String) cr.value(), IptvTask.class);
			log.info("---c2KafkaListener==="+iptvTask);

			//2,播控回掉 3,iptv回掉
			iptvTask.setProcesses(2);
			//0,待解析,1解析成功
			iptvTask.setStatus(0);
			saveOrUpdateSoapRequestByCorrelateId(iptvTask);
			handleIptvTaskList(iptvTask);
		}catch (Exception e) {
			log.error("---c2KafkaListener Exception===", e);
		}
	}
	
	

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值