1

totally new to java.

writing a spring-kafka app, which has the following Kafka listener method:

@KafkaListener(id = "receiver-api",
            topicPartitions =
                    { @TopicPartition(topic = "topic1",
                            partitionOffsets = @PartitionOffset(partition = "0", initialOffset = "0")))})
    public void receiveMessage(String message) {
        try {
            JSONObject incomingJsonObject = new JSONObject(message);

                handleMessage(incomingJsonObject);
            }   

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

I've been asked to refactor this part of the app into a separate stand-alone package, so the "receiveMessage" could be called, and a method / function could be passed to it, in place of "handleMessage", to process each incoming message.

This "receiveMessage" method never returns, as it keeps listening on a Kafka topic.

What would be the proper syntax, to change / add in this method, so it could be called as a package / library, and a message handling method would be passed to it by the calling app:

...

import kafkaReceiver;

messageHandler(String message){
......
}

kafkaReceiver.receiveMessage(messageHandler);
4

1 回答 1

1

它是Java。没有这样的概念method to method。有一些对象,通常称为services. 因此,您可以提取您的@KafkaListener服务并为其注入适当的服务实现:

public class MyKafkaListener {

    private final MyService myService;

    public MyKafkaListener(MyService myService) {
        this.myService = myService;
    }


    @KafkaListener
    public void receiveMessage(String message) {
            this.myService.handleMessage(message);
    }

}

...

@Bean
public MyKafkaListener myKafkaListener() {
   return new MyKafkaListener(myServiceImpl());
}
于 2016-11-03T14:17:33.990 回答