为了账号安全,请及时绑定邮箱和手机立即绑定

spring Kafka 模型不在受信任的包中

spring Kafka 模型不在受信任的包中

桃花长相依 2022-06-15 10:05:25
我正在与spring-Kafka-2.1.5和一起开发微服务spring-boot-2.0.5第一个服务将向 kafka 生成一些消息,第二个服务将使用它们,而消费我遇到了问题Caused by: java.lang.IllegalArgumentException: The class 'com.service1.model.TopicMessage' is not in the trusted packages: [java.util, java.lang, com.service2.model.ConsumeMessage]. If you believe this class is safe to deserialize, please provide its name. If the serialization is only done by a trusted source, you can also enable trust all (*).因此,从错误消息来看,这是com.service1.model.TopicMessageservice1 的序列化模型。但我正在尝试将消息反序列化为com.service2.model.ConsumeMessageservice2 中的模型并遇到此问题我在这里发现了同样的问题,并尝试了以下格式以及文档文档下面是我的配置  @Bean(name = "kafkaConsumerConfig")   public Map<String, Object> kafkaConsumerConfig() {    Map<String, Object> props = new HashMap<>();    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);    props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);    props.put(ConsumerConfig.CLIENT_ID_CONFIG, clientId);    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, offsetconfig);    props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, autoCommitInterval);    props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, sessionTimeout);    props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, maxPollRecords);    props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, enableAutoCommit);     }kafka消费者工厂@Bean(name = "kafkaConsumerFactory")public ConsumerFactory<String, ConsumeMessage> kafkaConsumerFactory()        {    JsonDeserializer<ConsumeMessage>     deserializer = new JsonDeserializer<>();    deserializer.addTrustedPackages("com.service2.model");return new DefaultKafkaConsumerFactory<String, ConsumeMessage>(kafkaConsumerConfig(),new StringDeserializer(),deserializer);}}
查看完整描述

1 回答

?
喵喵时光机

TA贡献1846条经验 获得超7个赞

您需要header precedence在反序列化器中禁用:


/**

 * Construct an instance with the provided target type, and

 * useHeadersIfPresent with a default {@link ObjectMapper}.

 * @param targetType the target type.

 * @param useHeadersIfPresent true to use headers if present and fall back to target

 * type if not.

 * @since 2.2

 */

public JsonDeserializer(Class<? super T> targetType, boolean useHeadersIfPresent) {

useHeadersIfPresent参数必须配置false为. 这样inferred,将使用一种类型,并且将忽略标头值。


如果你不使用,你应该考虑用类似的逻辑spring-kafka-2.2实现你自己的: https ://github.com/spring-projects/spring-kafka/blob/master/spring-kafka/src/main/java/org/ springframework/kafka/support/serializer/JsonDeserializer.javaJsonDeserializer


查看完整回答
反对 回复 2022-06-15
  • 1 回答
  • 0 关注
  • 105 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信