简体   繁体   English

发送到 kafka 主题时序列化消息时出错

[英]Error to serialize message when sending to kafka topic

i need to test a message, which contains headers, so i need to use MessageBuilder, but I can not serialize.我需要测试一条消息,其中包含标题,所以我需要使用 MessageBuilder,但我无法序列化。

I tried adding the serialization settings on the producer props but it did not work.我尝试在 producer 道具上添加序列化设置,但它没有用。

Can someone help me?有人能帮我吗?

this error:这个错误:

org.apache.kafka.common.errors.SerializationException: Can't convert value of class org.springframework.messaging.support.GenericMessage to class org.apache.kafka.common.serialization.StringSerializer specified in value.serializer

My test class:我的测试class:

public class TransactionMastercardAdapterTest extends AbstractTest{

@Autowired
private KafkaTemplate<String, Message<String>> template;

@ClassRule
public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1);

@BeforeClass
public static void setUp() {
    System.setProperty("spring.kafka.bootstrap-servers", embeddedKafka.getBrokersAsString());
    System.setProperty("spring.cloud.stream.kafka.binder.zkNodes", embeddedKafka.getZookeeperConnectionString());
}

@Test
public void sendTransactionCommandTest(){

    String payload = "{\"o2oTransactionId\" : \"" + UUID.randomUUID().toString().toUpperCase() + "\","
            + "\"cardId\" : \"11\","
            + "\"transactionId\" : \"20110405123456\","
            + "\"amount\" : 200.59,"
            + "\"partnerId\" : \"11\"}";

    Map<String, Object> props = KafkaTestUtils.producerProps(embeddedKafka);
    props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

    Producer<String, Message<String>> producer = new KafkaProducer<>(props);
    producer.send(new ProducerRecord<String, Message<String>> ("notification_topic", MessageBuilder.withPayload(payload)
            .setHeader("status", "RECEIVED")
            .setHeader("service", "MASTERCARD")
            .build()));

    Map<String, Object> configs = KafkaTestUtils.consumerProps("test1", "false", embeddedKafka);

    configs.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
    ConsumerFactory<byte[], byte[]> cf = new DefaultKafkaConsumerFactory<>(configs);

    Consumer<byte[], byte[]> consumer = cf.createConsumer();
    consumer.subscribe(Collections.singleton("transaction_topic"));
    ConsumerRecords<byte[], byte[]> records = consumer.poll(10_000);
    consumer.commitSync();

    assertThat(records.count()).isEqualTo(1);
}

} }

I'd say the error is obvious:我会说错误很明显:

Can't convert value of class org.springframework.messaging.support.GenericMessage to class org.apache.kafka.common.serialization.StringSerializer specified in value.serializer

Where your value is GenericMessage , but StringSerializer can work only with strings.您的值是GenericMessage ,但StringSerializer只能与字符串一起使用。

What you need is called JavaSerializer which does not exist, but not so difficult to write:您需要的称为JavaSerializer ,它不存在,但编写起来并不难:

public class JavaSerializer implements Serializer<Object> {

    @Override
    public byte[] serialize(String topic, Object data) {
        try {
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            ObjectOutputStream objectStream = new ObjectOutputStream(byteStream);
            objectStream.writeObject(data);
            objectStream.flush();
            objectStream.close();
            return byteStream.toByteArray();
        }
        catch (IOException e) {
            throw new IllegalStateException("Can't serialize object: " + data, e);
        }
    }

    @Override
    public void configure(Map<String, ?> configs, boolean isKey) {

    }

    @Override
    public void close() {

    }

}

And configure it for that value.serializer property.并为该value.serializer属性配置它。

private void configureProducer() {
Properties props = new Properties();
props.put("key.serializer",
        "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer",
        "org.apache.kafka.common.serialization.ByteArraySerializer");

producer = new KafkaProducer<String, String>(props);

} }

This will do the job.这将完成这项工作。

在我的情况下,我使用的是 spring cloud 并且没有在属性文件中添加以下属性

spring.cloud.stream.kafka.binder.configuration.value.serializer=org.apache.kafka.common.serialization.StringSerializer

This is what I used and it worked for me这是我用过的,对我有用

Map<String, Object> configProps = new HashMap<>();
configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, org.apache.kafka.common.serialization.StringSerializer.class);
configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, org.springframework.kafka.support.serializer.JsonSerializer.class);

spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.IntegerSerializer spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.IntegerSerializer spring.kafka.producer.value-serializer=org.apache.kafka.common.StringSerialization.

使用@XmlRootElement注释 JSON 类

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 kafka-错误将消息发送到主题test-topic时发生错误,键为:null,值:17个字节,错误 - kafka - ERROR Error when sending message to topic test-topic with key: null, value: 17 bytes with error 向主题发送消息时,minikube 上的 Kafka 控制台生产者/消费者出错 - Kafka console producer/consumer on minikube ERROR Error when sending message to topic Kafka Console Producer - 向主题发送消息时出错:TimeoutException:Expired 1 record - Kafka Console Producer - Error when sending message to topic : TimeoutException: Expiring 1 record ERROR 向主题发送消息时出错 - ERROR Error when sending message to topic Kafka基本设置创建主题并发送消息时出现错误消息 - Error message with Kafka basic setup creating topic and sending messages 发送到 Kafka 主题时反序列化 object 时出错 - Error while Deserializing object when sending to Kafka topic 将消息发布到Kafka主题时出错 - Error in Publishing message to Kafka topic Kafka 向 Spark Streaming 发送消息时出错 - Error When Kafka Sending Message to Spark Streaming 当发送到通过AdminClient createTopics方法创建的主题时,Kafka生产者抛出“接收到的未知主题或分区错误” - Kafka producer throws “Received unknown topic or partition error” when sending to topic created via AdminClient createTopics method 如何 JSON 序列化消息并使用 JSON 架构将其发布到 Kafka 主题 - How to JSON serialize message and post it to Kafka Topic with JSON Schema
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM