Java Kafka adminClient 主题配置。配置值被覆盖

2024-02-29

在尝试使用 java kafka adminClient 配置新创建的 kafka 主题时,值被覆盖。

我尝试使用控制台命令设置相同的主题配置,并且它有效。不幸的是,当我尝试通过 Java 代码时,一些值发生冲突并被覆盖。

ConfigResource resource = new ConfigResource(ConfigResource.Type.TOPIC, topicName);
Map<ConfigResource, Config> updateConfig = new HashMap<>();

// update retention Bytes for this topic
ConfigEntry retentionBytesEntry = new ConfigEntry(TopicConfig.RETENTION_BYTES_CONFIG, String.valueOf(retentionBytes));
updateConfig.put(resource, new Config(Collections.singleton(retentionBytesEntry)));

// update retention ms for this topic
ConfigEntry retentionMsEntry = new ConfigEntry(TopicConfig.RETENTION_MS_CONFIG, String.valueOf(retentionMs));
updateConfig.put(resource, new Config(Collections.singleton(retentionMsEntry)));

// update segment Bytes for this topic
ConfigEntry segmentBytesEntry = new ConfigEntry(TopicConfig.SEGMENT_BYTES_CONFIG, String.valueOf(segmentbytes));
updateConfig.put(resource, new Config(Collections.singleton(segmentBytesEntry)));

// update segment ms for this topic
ConfigEntry segmentMsEntry = new ConfigEntry(TopicConfig.SEGMENT_MS_CONFIG, String.valueOf(segmentMs));
updateConfig.put(resource, new Config(Collections.singleton(segmentMsEntry)));

// Update the configuration
client.alterConfigs(updateConfig);

我希望该主题正确地包含所有给定的配置值。


您的逻辑无法正常工作,因为您调用了Map.put()使用同一把钥匙多次。因此仅保留最后一个条目。

指定多个主题配置的正确方法是将它们添加到ConfigEntry目的。仅在添加后ConfigEntry to the Map.

例如:

// Your Topic Resource
ConfigResource cr = new ConfigResource(Type.TOPIC, "mytopic");

// Create all your configurations
Collection<ConfigEntry> entries = new ArrayList<>();
entries.add(new ConfigEntry(TopicConfig.SEGMENT_BYTES_CONFIG, String.valueOf(segmentbytes)));
entries.add(new ConfigEntry(TopicConfig.RETENTION_BYTES_CONFIG, String.valueOf(retentionBytes)));
...

// Create the Map
Config config = new Config(entries);
Map<ConfigResource, Config> configs = new HashMap<>();
configs.put(cr, config);

// Call alterConfigs()
admin.alterConfigs(configs);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java Kafka adminClient 主题配置。配置值被覆盖 的相关文章

随机推荐