将BlockingQueue传递给Spring KafkaListener

问题描述 投票:0回答:1

我是Java,Spring和Kafka的新手。情况如下:

我使用了@KafkaListener注释来创建一个看起来像这样的Kafka Consumer:

public class Listener {

private ExecutorService executorService;
private List<Future> futuresThread1 = new ArrayList<>();
public Listener() {
    Properties appProps = new AppProperties().get();
    this.executorService = Executors.newFixedThreadPool(Integer.parseInt(appProps.getProperty("listenerThreads")));
}
//TODO: how can I pass an approp into this annotation?
@KafkaListener(id = "id0", topics = "bose.cdp.ingest.marge.boseaccount.normalized")
public void listener(ConsumerRecord<?, ?> record, ArrayBlockingQueue<ConsumerRecord> arrayBlockingQueue) throws InterruptedException, ExecutionException
    {
        futuresThread1.add(executorService.submit(new Runnable() {
                @Override public void run() {
                    System.out.println(record);
                    arrayBlockingQueue.add(record);
                }
        }));
    }

}

我向监听器添加了一个参数ArrayBlockingQueue,我希望它能够将来自Kafka的消息添加到。

我遇到的问题是我无法弄清楚我是如何实际将ArrayBlockingQueue传递给监听器的,因为Spring正在处理实例化并在后台运行监听器。

我需要这个阻塞队列,以便侦听器之外的另一个对象可以访问消息并使用它进行一些操作。例如,在我的主要:

@SpringBootApplication
public class SourceAccountListenerApp {
    public static void main(String[] args) {
        Properties appProps = new AppProperties().get();
        ArrayBlockingQueue<ConsumerRecord> arrayBlockingQueue = new ArrayBlockingQueue<>(
           Integer.parseInt(appProps.getProperty("blockingQueueSize"))
        );
        //TODO: This starts my listener. How do I pass the queue to it?
        SpringApplication.run(SourceAccountListenerApp.class, args);
    }
}
java spring apache-kafka listener spring-kafka
1个回答
2
投票

有很多方法可以将阻塞队列声明为bean。

一个例子,主要:

@SpringBootApplication
public class SourceAccountListenerApp {
    public static void main(String[] args) {
        SpringApplication.run(SourceAccountListenerApp.class, args);
    }

    @Bean
    public ArrayBlockingQueue arrayBlockingQueue() {
        Properties appProps = new AppProperties().get();
        ArrayBlockingQueue<ConsumerRecord> arrayBlockingQueue = new ArrayBlockingQueue<>(
           Integer.parseInt(appProps.getProperty("blockingQueueSize"))
        );
        return arrayBlockingQueue;
    }
}

监听器:

public class Listener {

    @Autowired
    ArrayBlockingQueue arrayBlockingQueue;
© www.soinside.com 2019 - 2024. All rights reserved.