Spring Cloud Stream中每个绑定的自定义键序列

时间:2019-05-09 09:43:25

标签: spring-cloud-stream spring-kafka

我试图了解如何在Spring Cloud Stream中使用其他密钥序列化器/反序列化器。我已经找到了指定全局Serdes的方法,但是我不明白如何为每个绑定指定不同的Serdes,以允许使用不同的键类型(整数,字符串等)。 例如,以下配置使用属性spring.kafka.consumer.keyDeserializerspring.kafka.producer.keySerializer指定全局密钥Serdes:

spring:
  cloud:
    stream:
      bindings:
        input:
          contentType: application/*+avro
          destination: user                    
          group: my-group
        output:
          contentType: application/*+avro
          destination: user     
          producer:
            partition-count: 2      
      kafka:
        binder:
          brokers: default:9092
      schemaRegistryClient:
        endpoint: http://default:8081
  kafka:
    consumer:
      keyDeserializer: org.apache.kafka.common.serialization.StringDeserializer
    producer:
      keySerializer: org.apache.kafka.common.serialization.StringSerializer

我可以使用以下代码段来消费和产生消息密钥:

// Consumer
@StreamListener(Sink.INPUT)
    public void handle(@Payload UserValue user, @Headers Map<String, Object> headers,
            @Header(KafkaHeaders.RECEIVED_MESSAGE_KEY) String key) {
        System.out.println("Received: " + user + " with key: " + key + " and headers: " + headers);
    }

// Producer
UserValue user = UserValue.newBuilder().setName("Alessandro").setSurname("Dionisi").build();
        output.send(MessageBuilder.withPayload(user).setHeader(KafkaHeaders.MESSAGE_KEY, "1").build());

1 个答案:

答案 0 :(得分:1)

您可以通过configuration属性

完成操作

spring.cloud.stream.kafka.bindings.<bindingName>.consumer.configuration.<whatever-kafka-property-name>=. . .

查看更多信息here