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

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

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

@SpringBootApplication
@DirtiesContext
@EmbeddedKafka(topics = "TEST_TOPIC.P2.R2", partitions = 1, controlledShutdown = false, brokerProperties = {
        "listeners=PLAINTEXT://localhost:9092", "port=9092" })
public class MockKafkaProducerApplication {

    public static void main(String[] args) throws Exception {
        System.out.println("Starting Spring boot Application");
        SpringApplication.run(MockKafkaProducerApplication.class, args);

    }

}

@ActiveProfiles("kafka_test")
@Configuration
public class KafkaConsumerTestBase {
    private Logger LOGGER = LoggerFactory.getLogger(KafkaConsumerTestBase.class);

    @Autowired
    protected EmbeddedKafkaBroker embeddedKafka;

    @Value("${spring.embedded.kafka.brokers}")
    private String brokerAddress;

    @Autowired
    protected KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;

    @Autowired
    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如何运行它:

public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
    Optional<AnnotatedElement> element = context.getElement();
    if (element.isPresent() && !this.springTestContext((AnnotatedElement)element.get())) {
        EmbeddedKafka embedded = (EmbeddedKafka)AnnotatedElementUtils.findMergedAnnotation((AnnotatedElement)element.get(), EmbeddedKafka.class);
        if (embedded != null) {
            EmbeddedKafkaBroker broker = this.getBrokerFromStore(context);
            if (broker == null) {
                broker = this.createBroker(embedded);
                BROKERS.set(broker);
                this.getStore(context).put("embedded-kafka", broker);
            }
        }
    }

    return ConditionEvaluationResult.enabled("");
}

private boolean springTestContext(AnnotatedElement annotatedElement) {
    return AnnotatedElementUtils.findAllMergedAnnotations(annotatedElement, ExtendWith.class).stream().filter((extended) -> {
        return Arrays.asList(extended.value()).contains(SpringExtension.class);
    }).findFirst().isPresent();
}

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

相关问题