Spring Boot / Spring Kafka中的KafkaTemplate抛出NullPointerException

时间:2019-05-02 06:48:56

标签: spring spring-boot apache-kafka

我正在使用KafkaTemplate类从Kafka集群接收数据到我的Spring Boot应用程序。第一个数据已完美接收,但在此之后我得到了NullPointerException。

这是我设置的Producerconfig:

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class KafkaProducerConfig {

    @Value("localhost:9092")
    private String bootstrapServers;

    @Bean
    public Map<String, Object> producerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        return props;
    }

    @Bean
    public ProducerFactory<String, String> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }
}

我在另一个类中使用KafkaTemplate,这是抛出NullPointerException的方法:

@Autowired
    private KafkaTemplate<String, String> kafkaTemplate;


    public void sendMessage(@NonNull String message) {
        log.info(String.format("#### -> Producing message -> %s", message));
        //This is where the Exception is thrown
        this.kafkaTemplate.send(TOPIC, message);
    }

0 个答案:

没有答案