簡體   English   中英

嵌入式 kafka 與真實類通信

[英]Embedded kafka with real classes communication

我有 Spring 使用spring-kafkaspring-kafka-test引導應用程序。 我有下面的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 而沒有任何 mocking class。 我嘗試使用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.

有人可以讓我知道如何在沒有 mocking 任何類的情況下為我的 kafka 生產者編寫 Junit,它應該使用真實類進行測試。

是的,我嘗試了以下實現,它對我有用。 你可以試試這個。 如果我需要任何進一步的幫助,請告訴我。

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM