简体   繁体   English

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

[英]Java Kafka adminClient topic configuration. Configuration values are overwritten

While trying to configure a newly created kafka topic, using java kafka adminClient, values are overwritten. 尝试使用java kafka adminClient配置新创建的kafka主题时,值将被覆盖。

I have tried to set the same topic configuration using console commands and it works. 我尝试使用控制台命令设置相同的主题配置,并且它可以正常工作。 Unfortunately when I try through Java code some values collide and are overwritten. 不幸的是,当我尝试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);

I expect the topic to have all given configuration values correctly. 我希望该主题正确地具有所有给定的配置值。

Your logic is not working correctly because you call Map.put() several times with the same key. 您的逻辑无法正常工作,因为您使用相同的键多次调用Map.put() Hence only the last entry is kept. 因此,仅保留最后一个条目。

The correct way to specify multiple topic configurations is to add them in the ConfigEntry object. 指定多个主题配置的正确方法是将它们添加到ConfigEntry对象中。 Only after add the ConfigEntry to the Map . 仅在将ConfigEntry添加到Map

For example: 例如:

// 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM