【问题标题】:Embedded kafka with real classes communication嵌入式 kafka 与真实类通信
【发布时间】:2022-01-11 07:15:02
【问题描述】:

我有使用 spring-kafkaspring-kafka-test 的 Spring Boot 应用程序。我有下面的 MessageProducer。

@Component
public class MessageProducer {
   private KafkaTemplate<String, String> kafkaTemplate;

   @Autowired
   public MessageProducer(KafkaTemplate<String, String> kafkaTemplate) {
       this.kafkaTemplate = kafkaTemplate;
   }

   public void sendMessage(String message, String topicName) {
       kafkaTemplate.send(topicName, message);
   }
}

我想为上面编写 Junit 而不模拟类。我尝试使用EmbeddedKafkaRule ,但我不确定如何将其连接到我的应用程序定义的 kafka 代理,因此当我发送有关主题的消息时,消费者(其中存在@kafkaLister)应该选择消息并处理它。

EmbeddedKafkaRule 我也遇到了错误。

 [Producer clientId=producer-1] Connection to node 0 (localhost/192.168.0.24:57516) could not be established. Broker may not be available.

谁能告诉我如何在不模拟任何类的情况下为我的 kafka 制作人编写一个 Junit,它应该使用真实的类进行测试。

【问题讨论】:

    标签: spring-boot spring-kafka spring-kafka-test


    【解决方案1】:

    是的,我尝试了以下实现,它对我有用。你可以试试这个。如果我需要任何进一步的帮助,请告诉我。

    import java.util.concurrent.TimeUnit;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    import com.the.basic.tech.info.kafka.consumer.Receiver;
    import com.the.basic.tech.info.kafka.producer.Sender;
    import com.the.basic.tech.info.model.Employee;
    
    @SpringBootApplication
    public class SpringKafkaApplication implements CommandLineRunner {
    
        @Autowired
        Sender sndr;
        
        @Autowired
        Receiver rcvr;
        
      public static void main(String[] args) {
        SpringApplication.run(SpringKafkaApplication.class, args);
      }
      
        @Override
        public void run(String... arg0) throws Exception {
            Employee employee = new Employee("2121", "John", "Dept-A", "3000", "30", "California");
            sndr.send(employee);
    
            rcvr.getLatch().await(10000, TimeUnit.MILLISECONDS);
        }
    }
    

    示例项目 [Spring Boot + Spring Kafka with Zookeeper + JSON 序列化 |反序列化+示例] https://thebasictechinfo.com/java-8/spring-boot-spring-kafka-with-zookeeper-json-serialization-deserialization-example/

    【讨论】:

    • 您好 Pankaj,感谢您的回复。我试图使用上述解决方案,但我收到 org.junit.internal.runners.rules.ValidationError: The @ClassRule 'embeddedKafka' must implement TestRule. 这个错误
    • 你能分享你的代码快照吗..我可以帮助你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多