springboot kafka @KafkaListener 动态指定topics

@Configuration
@Slf4j
public class KafkaConfig implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        String topicName = wireTopics();
        System.setProperty("topicName", topicName);
        log.info("### set system config topic:{}", topicName);
    }

    private String wireTopics(){
        Set topicSet = new HashSet<>();
        for(KafkaTopicEnum topicEnum : KafkaTopicEnum.values()){
            topicSet.add(topicEnum.getName());
        }
        return StringUtils.join(topicSet,",");
    }
}

配置文件初始化topic枚举类中的所有需要监听的topic,写入system的属性中。

service消费方法,注意topics属性的值,{"#{'${topicName}'.split(',')}"}

@KafkaListener(topics = {"#{'${topicName}'.split(',')}"})
public void consume(ConsumerRecord record){
    log.info("###receive message {"+record.key()+"} by <"+record.topic()+">");
    consumerService.operateConsumerRecord(record);
}

如果topic数量多,可以重复复制此方法,修改方法名即可。

以上代码亲测有效!!!

 

你可能感兴趣的:(kafka,java,Springboot)