SpringBoot找不到嵌入的Kafkabroker bean(不使用springboottest)

lnlaulya  于 2021-06-05  发布在  Kafka
关注(0)|答案(2)|浏览(603)

我想将嵌入式kafka用于spring引导应用程序。我可以使用嵌入的kafka进行junit测试,但是在尝试在主应用程序中使用时,嵌入的kafka对象没有被识别。
当尝试加载spring引导应用程序时,嵌入的kafka对象没有自动连接。这是非测试流。

  1. @SpringBootApplication
  2. @DirtiesContext
  3. @EmbeddedKafka(topics = "TEST_TOPIC.P2.R2", partitions = 1, controlledShutdown = false, brokerProperties = {
  4. "listeners=PLAINTEXT://localhost:9092", "port=9092" })
  5. public class MockKafkaProducerApplication {
  6. public static void main(String[] args) throws Exception {
  7. System.out.println("Starting Spring boot Application");
  8. SpringApplication.run(MockKafkaProducerApplication.class, args);
  9. }
  10. }
  11. @ActiveProfiles("kafka_test")
  12. @Configuration
  13. public class KafkaConsumerTestBase {
  14. private Logger LOGGER = LoggerFactory.getLogger(KafkaConsumerTestBase.class);
  15. @Autowired
  16. protected EmbeddedKafkaBroker embeddedKafka;
  17. @Value("${spring.embedded.kafka.brokers}")
  18. private String brokerAddress;
  19. @Autowired
  20. protected KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;
  21. @Autowired
  22. protected KafkaTemplate<String, String> senderTemplate;

....... ........ }
com.dell.pde.kafka.kafkaconsumertestbase中的字段embeddedkafka需要类型为“org.springframework.kafka.test.embeddedkafkabroker”的bean,但找不到该bean。
注入点具有以下注解:-@org.springframework.beans.factory.annotation.autowired(required=true)

hpcdzsge

hpcdzsge1#

嵌入式Kafka是为了测试,而不是实际应用。
可以在运行基于spring-kafka的测试的测试类上指定的注解。在常规spring testcontext框架之上提供以下功能:
...
提供内存中kafka示例以运行测试的库。
如果你想制作一个实际的模型应用程序,你还必须运行一个实际的Kafka示例。

ruyhziif

ruyhziif2#

@接口嵌入kafka-its用于测试目的。如果你检查 public class EmbeddedKafkaCondition 您可以看到spring如何运行它:

  1. public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
  2. Optional<AnnotatedElement> element = context.getElement();
  3. if (element.isPresent() && !this.springTestContext((AnnotatedElement)element.get())) {
  4. EmbeddedKafka embedded = (EmbeddedKafka)AnnotatedElementUtils.findMergedAnnotation((AnnotatedElement)element.get(), EmbeddedKafka.class);
  5. if (embedded != null) {
  6. EmbeddedKafkaBroker broker = this.getBrokerFromStore(context);
  7. if (broker == null) {
  8. broker = this.createBroker(embedded);
  9. BROKERS.set(broker);
  10. this.getStore(context).put("embedded-kafka", broker);
  11. }
  12. }
  13. }
  14. return ConditionEvaluationResult.enabled("");
  15. }
  16. private boolean springTestContext(AnnotatedElement annotatedElement) {
  17. return AnnotatedElementUtils.findAllMergedAnnotations(annotatedElement, ExtendWith.class).stream().filter((extended) -> {
  18. return Arrays.asList(extended.value()).contains(SpringExtension.class);
  19. }).findFirst().isPresent();
  20. }

尝试覆盖此类以在应用程序上运行它。
我建议你直接用docker来提升Kafka的形象。

展开查看全部

相关问题