多topic注入kafka消费者
AI-摘要
新 · 都在 GPT
AI初始化中...
介绍自己
生成本文简介
推荐相关文章
前往主页
前往tianli博客
多topic注入kafka消费者
@KafkaListener() 两种方式加载多个topic
# application.properties
spring.kafkaListenerList = topic1,topic2
第一种
通过EL表达式进行注入
@KafkaListener(topics = "#{'${spring.kafkaListenerList}'.split(',')}")
第二种
通过解析数据生成对象进行注入
KafkaListenerReceiver
是自定义的消费对象
- KafkaListenerConfig.java
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
@Configuration
@Slf4j
public class KafkaListenerConfig implements BeanDefinitionRegistryPostProcessor, PriorityOrdered {
private List<String> listenerList;
KafkaListenerConfig() throws IOException {
Properties pro = new Properties();
File f;
f =new File( java.net.URLDecoder.decode(this.getClass().getResource("/application.properties").getPath(),"utf-8"));
FileInputStream in = new FileInputStream(f);
pro.load(in);
in.close();
String listString = pro.getProperty("spring.verify.kafkaListenerList");
if (StringUtils.isEmpty(listString)){
log.error("spring.verify.kafkaListenerList is empty or null");
System.exit(0);
}
log.info("spring.kafkaListenerList: "+listString);
listenerList = Arrays.asList(listString.split(","));
}
public List<String> getListenerList() {
return listenerList;
}
public void setListenerList(List<String> listenerList) {
this.listenerList = listenerList;
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
for (String listener : listenerList) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(KafkaListenerReceiver.class);
builder.addConstructorArgValue(listener);
beanDefinitionRegistry.registerBeanDefinition(listener, builder.getBeanDefinition());
}
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
- KafkaListenerReceiver.java
@KafkaListener(topics = "#{__listener.topic}")
- 感谢你赐予我前进的力量
赞赏者名单
因为你们的支持让我意识到写文章的价值🙏
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 Carol 小屋
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果