如何为春季卡夫卡设置protobuf参数?

时间:2018-07-06 07:07:36

标签: java spring spring-boot protocol-buffers spring-kafka

问题:https://github.com/spring-projects/spring-kafka/issues/727

请阅读上面的链接,谢谢!

当我使用spring-boot和spring-kafka时,我的代码如下:

# application.properties
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=mock-test
spring.kafka.consumer.key- deserializer=org.apache.kafka.common.serialization.StringDeserializer
# HERE: how should I set value serializer for proto message???
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.BytesDeserializer
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.BytesSerializer

我的Kafka生产者代码如下:

@Component
public class Sender {
    @Autowired
    private KafkaTemplate<Object, MockEvent> kafkaTemplate;

    public void send(MockEvent events) {
        kafkaTemplate.send(Kafka.TOPIC, events);
    }
}

MockEvent是protobuf消息。

mvn compile正常时,但运行时将出错:

2018-07-06 15:52:24.334  INFO 79274 --- [nio-8080-exec-1] o.a.kafka.common.utils.AppInfoParser     : Kafka version : 1.0.1
2018-07-06 15:52:24.334  INFO 79274 --- [nio-8080-exec-1] o.a.kafka.common.utils.AppInfoParser     : Kafka commitId : c0518aa65f25317e
org.apache.kafka.common.errors.SerializationException: Can't convert value of class com.mock.event.MockEvent to class 
org.apache.kafka.common.serialization.BytesSerializer specified in value.serializer
Caused by: java.lang.ClassCastException: com.mock.event.MockEvent cannot be cast to org.apache.kafka.common.utils.Bytes
        at org.apache.kafka.common.serialization.BytesSerializer.serialize(BytesSerializer.java:23)
        at org.apache.kafka.common.serialization.ExtendedSerializer$Wrapper.serialize(ExtendedSerializer.java:65)
        at org.apache.kafka.common.serialization.ExtendedSerializer$Wrapper.serialize(ExtendedSerializer.java:55)
        at org.apache.kafka.clients.producer.KafkaProducer.doSend(KafkaProducer.java:791)
        at org.apache.kafka.clients.producer.KafkaProducer.send(KafkaProducer.java:768)
        at org.springframework.kafka.core.DefaultKafkaProducerFactory$CloseSafeProducer.send(DefaultKafkaProducerFactory.java:285)
        at org.springframework.kafka.core.KafkaTemplate.doSend(KafkaTemplate.java:349)
        at org.springframework.kafka.core.KafkaTemplate.send(KafkaTemplate.java:182)

非常感谢,因为我想发送一封原始消息。

1 个答案:

答案 0 :(得分:2)

您的值序列化器与MockEvent不兼容。

您需要将Bytes作为消息传递给Kafka,而不是MockEvent

看看serializeorg.apache.kafka.common.serialization.BytesSerializer方法的参数。

我认为最好的选择是选择其他序列化器或创建自己的自定义序列化器/反序列化器以处理MockEvent。这样,您只需将MockEvent传递给Kafka。

我从未使用过protobuf消息,也不知道它是什么。但是您的stacktrace对错误非常具体。