Spring Cloud合同-没有为主题设置消费者[...]

时间:2019-12-20 10:43:01

标签: java spring apache-kafka spring-kafka spring-cloud-contract

我目前正在使用Spring Cloud Contracts开发API兼容性检查。我按照文档说明设置了所有内容。但是我遇到了一个问题-java.lang.IllegalStateException: No consumer set up for topic [testSyncTopic]。该异常在KafkaStubMessages类中引发。因此,我认为这是与图书馆有关的问题。在我的项目中,我有两个单独的Maven项目。他们每个人都是消费者和生产者(单独的主题)。我的合同放在其他存储库中。

所以...我目前正在研究以下场景: 我们有2个模块-模块A和B。模块A向主题为T1和T2的Kafka主题t1和t2发送消息,并从主题T3和T4接收消息t3和t4。模块B从T1和T2接收并发送到T3和T4。

所有使用者测试均通过每个模块。但是生产者测试最终会出现主题中提到的错误。

我怀疑这是由存根创建错误引起的。因此未设置适当的侦听器。

我尝试了不同的kafka配置,但我认为并非如此。我还检查了Spring Cloud Contracts配置,但是一切似乎都正常。生成带有存根的正确罐子。不幸的是,Google在这方面没有太大帮助。

如果您需要任何信息以帮助我,请随时提问。 我现在正在处理这几天,所以我很拼命,真的需要您的帮助。

编辑:添加了堆栈跟踪和相关代码段

堆栈跟踪:

java.lang.IllegalStateException: No consumer set up for topic [testSyncTopic]

at org.springframework.cloud.contract.verifier.messaging.kafka.Receiver.receive(KafkaStubMessages.java:110)
at org.springframework.cloud.contract.verifier.messaging.kafka.KafkaStubMessages.receive(KafkaStubMessages.java:80)
at org.springframework.cloud.contract.verifier.messaging.kafka.KafkaStubMessages.receive(KafkaStubMessages.java:42)
at com.comarch.fsm.dispatcher.rest.ContractBaseTest.setup(ContractBaseTest.groovy:56)

基本测试类的配置:

@SpringBootTest
@EmbeddedKafka(bootstrapServersProperty = "spring.kafka.bootstrap-servers", brokerProperties = ["log.dir=target/embedded-kafka"])
@AutoConfigureStubRunner
abstract class BaseTestConfig extends Specification {
}

我的合同定义:

Pattern customDateTime() {
    Pattern.compile('([0-9]{4})-(1[0-2]|0[1-9])-(0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])Z')
}

Contract.make {
    label("sync")
    input {
        triggeredBy("sync()")
    }
    outputMessage {
        sentTo("testSyncTopic")
        body(
                syncStart: $(customDateTime())
        )
    }
}

ContractBaseTest类:

abstract class ContractBaseTest extends BaseTestConfig {

    @Autowired
    private KafkaService kafkaService;

    def synchronizeData() {
        kafkaService.sendKafkaMessage("testSyncTopic", null, new SyncDto(new Date()));
    }
}

1 个答案:

答案 0 :(得分:0)

为什么您的基础测试课有@AutoConfigureStubRunner,而应该有@AutoConfigureMessageVerifier?看来您在混合消费者和生产者。

请在此处检查带有Kafka的制作人的示例:https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/master/producer_kafka。出于可读性原因,我将其复制粘贴到此处。

生产者

基类:https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/master/producer_kafka/src/test/java/com/example/BaseClass.java

package com.example;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
// remove::start[]
import org.springframework.cloud.contract.verifier.messaging.boot.AutoConfigureMessageVerifier;
import org.springframework.kafka.test.context.EmbeddedKafka;
// remove::end[]
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
// remove::start[]
@AutoConfigureMessageVerifier
@EmbeddedKafka(partitions = 1, topics = {"topic1"})
// remove::end[]
@ActiveProfiles("test")
public abstract class BaseClass {

    @Autowired
    Controller controller;

    public void trigger() {
        this.controller.sendFoo("example");
    }
}

在这里您可以找到控制器

package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.common.Foo1;

/**
 * @author Gary Russell
 * @since 2.2.1
 */
@RestController
public class Controller {

    @Autowired
    private KafkaTemplate<Object, Object> template;

    @PostMapping(path = "/send/foo/{what}")
    public void sendFoo(@PathVariable String what) {
        this.template.send("topic1", new Foo1(what));
    }

}

在这里您可以看到生产配置(application.yml

spring:
  kafka:
    producer:
      value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
logging.level.org.springframework.cloud.contract: debug

在这里您可以看到测试配置(application-test.yml

spring:
  kafka:
    bootstrap-servers: ${spring.embedded.kafka.brokers}
    consumer:
      properties:
        "key.serializer": "org.springframework.kafka.support.serializer.JsonSerializer"
        "key.deserializer": "org.springframework.kafka.support.serializer.JsonDeserializer"
      group-id: groupId

和合同(https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/master/producer_kafka/src/test/resources/contracts/shouldSendFoo.groovy

import org.springframework.cloud.contract.spec.Contract

Contract.make {
    label("trigger")
    input {
        triggeredBy("trigger()")
    }
    outputMessage {
        sentTo("topic1")
        body([
                foo: "example"
        ])
    }
}

消费者

现在是消费者的时间(https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/master/consumer_kafka

package com.example;

import org.assertj.core.api.BDDAssertions;
import org.awaitility.Awaitility;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
// remove::start[]
import org.springframework.cloud.contract.stubrunner.StubTrigger;
import org.springframework.cloud.contract.stubrunner.spring.AutoConfigureStubRunner;
import org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties;
import org.springframework.kafka.test.context.EmbeddedKafka;
// remove::end[]
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
// remove::start[]
@AutoConfigureStubRunner(ids = "com.example:beer-api-producer-kafka", stubsMode = StubRunnerProperties.StubsMode.LOCAL)
@EmbeddedKafka(topics = "topic1")
// remove::end[]
@ActiveProfiles("test")
public class ApplicationTests {

    // remove::start[]
    @Autowired
    StubTrigger trigger;
    @Autowired
    Application application;

    @Test
    public void contextLoads() {
        this.trigger.trigger("trigger");

        Awaitility.await().untilAsserted(() -> {
            BDDAssertions.then(this.application.storedFoo).isNotNull();
            BDDAssertions.then(this.application.storedFoo.getFoo()).contains("example");
        });
    }
    // remove::end[]

}