Spring Kafka生产者实现

需求

我们需要通过Spring Kafka库,将消息推送给Kafka的topic中。这里假设Kafka的集群和用户我们都有了。这里Kafka认证采取SASL_PLAINTEXT方式接入,SASL 采用 SCRAM-SHA-256 方式加解密。

pom.xml

xml 复制代码
<dependency>
	<groupId>org.springframework.kafka</groupId>
	<artifactId>spring-kafka</artifactId>
</dependency>

我这里不需要写版本号,应为我使用的Spring Boot。Spring Boot会自动帮我挑选spring-kafka应该使用哪个版本合适。

application.yml

yaml 复制代码
spring:
  kafka:
    producer:
	  # kafka集群地址
      bootstrap-servers: xx.xx.xx.xxx:9092,xx.xx.xx.xxx:9092,xx.xx.xx.xxx:9092
	  client-id: producer-dev
      # SASL_PLAINTEXT 接入方式
      security:
        protocol: SASL_PLAINTEXT
      # 反序列化方式
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.apache.kafka.common.serialization.StringSerializer
      properties:
        # SASL 采用 SCRAM-SHA-256 方式
        sasl:
          mechanism: SCRAM-SHA-256
    # jaas配置
    jaas:
      options:
        username: kafkauser
        password: kafkapwd
      enabled: true
      login-module: org.apache.kafka.common.security.scram.ScramLoginModule
      control-flag: required

以上,是关于Spring Kafka的全部配置。下面摘要出来的配置,是可以单独配置在配置中心的:

yaml 复制代码
topic:
  # 接收消息的主题配置
  save: hello_kafka_topic
spring:
  kafka:
    producer:
      client-id: producer-dev
      # kafka集群地址
      bootstrap-servers: xx.xx.xx.xxx:9092,xx.xx.xx.xxx:9092,xx.xx.xx.xxx:9092
    # jaas配置
    jaas:
      options:
        username: kafkauser
        password: kafkapwd

Java

KafkaProducerService.java

java 复制代码
public interface KafkaProducerService {

    /**
     * 转发消息到kafka
     */
    void sendToKafka(String msg);

}

KafkaProducerServiceImpl.java

java 复制代码
import cn.com.xxx.service.KafkaProducerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.kafka.core.KafkaProducerException;
import org.springframework.kafka.core.KafkaSendCallback;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;

import javax.annotation.Resource;

/**
 * 转发消息到kafka
 */
@RefreshScope
@Slf4j
@Service
public class KafkaProducerServiceImpl implements KafkaProducerService {

    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * kafka接收消息的主题
     */
    @Value("${topic.save}")
    private String topic;


    @Override
    public void sendToKafka(String msg) {
        log.info(String.format("$$$$ => Producing message: %s", msg));

        ProducerRecord<String, String> recordKafka = new ProducerRecord<>(topic, msg);

        ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(recordKafka);
        future.addCallback(new KafkaSendCallback<String, String>() {

            @Override
            public void onSuccess(SendResult<String, String> result) {
                log.info("成功发消息:{}给Kafka:{}", msg, result);
            }

            @Override
            public void onFailure(KafkaProducerException ex) {
                log.error("发消息:{}给Kafka:{}", msg, recordKafka, ex);
            }
        });
    }
}

到这里为止Spring Kafka生产者所有配置就都可以了。这里使用的异步监听kafka回调的方式发送消息。

总结

这里使用Spring Kafka库异回调步给Kafka消息。这里使用的Spring Kafka库是老版本,所以,这里的使用的回调类是ListenableFuture类。

参考:

相关推荐
ask_baidu12 小时前
KafkaUtils
kafka·bigdata
张3蜂13 小时前
深入理解 Python 的 frozenset:为什么要有“不可变集合”?
前端·python·spring
洛豳枭薰14 小时前
消息队列关键问题描述
kafka·rabbitmq·rocketmq
lucky670714 小时前
Spring Boot集成Kafka:最佳实践与详细指南
spring boot·kafka·linq
Coder_Boy_14 小时前
基于Spring AI的分布式在线考试系统-事件处理架构实现方案
人工智能·spring boot·分布式·spring
7哥♡ۣۖᝰꫛꫀꪝۣℋ15 小时前
Spring-cloud\Eureka
java·spring·微服务·eureka
袁煦丞 cpolar内网穿透实验室15 小时前
远程调试内网 Kafka 不再求运维!cpolar 内网穿透实验室第 791 个成功挑战
运维·分布式·kafka·远程工作·内网穿透·cpolar
岁岁种桃花儿16 小时前
CentOS7 彻底卸载所有JDK/JRE + 重新安装JDK8(实操完整版,解决kafka/jps报错)
java·开发语言·kafka
一灰灰blog16 小时前
Spring AI中的多轮对话艺术:让大模型主动提问获取明确需求
数据库·人工智能·spring