KafkaProducerConfig.java 1.57 KB
package cn.com.glsx.entmicro.config;

import java.util.Properties;
import kafka.javaapi.producer.Producer;
import kafka.producer.ProducerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author lichongyuan
 * @ClassName KafkaProducerConfig.java
 * @description: kafka生产消息
 * @createTime
 */
@Configuration
public class KafkaProducerConfig {

    /**
     * kafka 生产者服务端地址
     */
    @Value("${assign.zookeeper.connect.magic}")
    private String producerServers;

    @Bean("producer")
    public Producer getProducer() {
        return new Producer(new ProducerConfig(initProperties()));
    }

    private Properties initProperties() {
        Properties properties = new Properties();
        properties.setProperty("serializer.class", "kafka.serializer.DefaultEncoder");
        properties.setProperty("key.serializer.class", "kafka.serializer.DefaultEncoder");
        properties.setProperty("metadata.broker.list", producerServers);
        properties.put("request.required.acks", "1");    // 1: leader 确认, -1/all: 所有 ISR 副本确认
        properties.put("request.timeout.ms", "10000");       // 请求超时时间
        properties.put("message.send.max.retries", "3");     // 发送失败重试次数
        properties.put("retry.backoff.ms", "300");           // 重试间隔// 1: leader 确认, -1/all: 所有 ISR 副本确认
        properties.setProperty("producer.type", "sync");
        return properties;
    }

}