Spring-Boot使用Spring-Kafka生产者

本文介绍了一种使用Spring Boot框架配置Kafka的具体方法,并提供了一个简单的Kafka生产者服务实现示例,该服务能够异步发送消息到指定主题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

application.properties:

# Kafka
spring.kafka.bootstrap-servers=kafka1:9092,kafka2:9092,kafka3:9092
spring.kafka.producer.batch-size=10
spring.kafka.producer.buffer-memory=33554432
# Id to pass to the server when making requests; used for server-side logging.
spring.kafka.producer.client-id=s1
# Compression type for all data generated by the producer.
#spring.kafka.producer.compression-type=
# Serializer class for keys.
#spring.kafka.producer.key-serializer=
# When greater than zero, enables retrying of failed sends.
spring.kafka.producer.retries=3

使用KafkaTemplate发送消息:

package com.pasenger.kafka.producer.services;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * Kafka生产者
 * Created by Pasenger on 2017/3/16.
 */

@Service
@Setter
@Getter
@Slf4j
public class KafkaProducerService {

    @Autowired
    private KafkaTemplate<Integer, String> kafkaTemplate;

    /**
     * 发送Kafka消息
     *
     * @param topic     kafka topic
     * @param partition kafka partition
     * @param message   message
     */
    @Async
    public void send(String topic, int partition, String message) {
        kafkaTemplate.send(topic, partition, message);
        kafkaTemplate.flush();
    }
}

转载于:https://my.oschina.net/pasenger/blog/865333

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值