如何在 Spring Cloud Stream 项目中将传入的标头映射为 String 而不是 byte[]? [英] How can I map incoming headers as String instead of byte[] in my Spring Cloud Stream project?

查看:17
本文介绍了如何在 Spring Cloud Stream 项目中将传入的标头映射为 String 而不是 byte[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 Spring Cloud Stream 项目,它使用 Spring Integration DSL 流和 Kafka 绑定器.一切正常,但来自 Kafka 的消息头值以 byte[] 的形式到达.

I have a simple Spring Cloud Stream project using Spring Integration DSL flows and using the Kafka binder. Everything works great, but message header values coming from Kafka arrive as byte[].

这意味着我的 SI @Header 参数需要是 byte[] 类型.哪个有效,但最好将它们作为字符串(我关心的所有入站标头都是字符串值).

This means that my SI @Header parameters need to be of type byte[]. Which works, but it'd be nice to have them as Strings (all the inbound headers I care about are String values).

我已将 Kafka 客户端配置为使用 StringSerializer/StringDeserializer.我假设我还需要以某种方式告诉 Spring Kafka 哪些标头映射为字符串以及使用什么字符编码.

I've configured the Kafka clients to use StringSerializer/StringDeserializer. I assume I also need to somehow tell Spring Kafka which headers to map as Strings and what character encoding to use.

我显然在这里遗漏了一些东西.有什么提示吗?

I'm obviously missing something here. Any tips?

推荐答案

将 binder 属性 headerMapperBeanName 设置为 DefaultKafkaHeaderMapper bean 的 bean 名称.

Set the binder property headerMapperBeanName to the bean name of a DefaultKafkaHeaderMapper bean.

spring.cloud.stream.kafka.binder.headerMapperBeanName

KafkaHeaderMapper 的 bean 名称,用于将 spring-messaging 标头映射到 Kafka 标头和从 Kafka 标头映射.例如,如果您希望在对标头使用 JSON 反序列化的 DefaultKafkaHeaderMapper 中自定义受信任的包,请使用此选项.

The bean name of a KafkaHeaderMapper used for mapping spring-messaging headers to and from Kafka headers. Use this, for example, if you wish to customize the trusted packages in a DefaultKafkaHeaderMapper that uses JSON deserialization for the headers.

然后您可以指定要由映射器映射为字符串的标题:

You can then specify which headers you want to be mapped as Strings by the mapper:

/**
 * Set the headers to not perform any conversion on (except {@code String} to
 * {@code byte[]} for outbound). Inbound headers that match will be mapped as
 * {@code byte[]} unless the corresponding boolean in the map value is true,
 * in which case it will be mapped as a String.
 * @param rawMappedHeaders the header names to not convert and
 * @since 2.2.5
 * @see #setCharset(Charset)
 * @see #setMapAllStringsOut(boolean)
 */
public void setRawMappedHeaders(Map<String, Boolean> rawMappedHeaders) {

这篇关于如何在 Spring Cloud Stream 项目中将传入的标头映射为 String 而不是 byte[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆