注解处理用于发布订阅(pubsub)。

huangapple go评论99阅读模式
英文:

Annotation processing for pubsub

问题

我有一个使用 Kafka 实现发布订阅机制的第三方库。我有类似以下的代码来订阅主题:

DDS.createListener((topic) -> "对这个主题做些事情");

我想更进一步,想要创建一个如下所示的注解:

@Subscribe("topicName")
public void listen(Topic topic) {
    // 对这个主题做些事情
}

在处理注解时,我遇到了问题。

首先,我需要找到用 @Subscribe 注解标记的方法,然后需要在幕后监听相关主题,当接收到主题时,将其传递给被注解的方法,在示例中即为 "listen" 方法。
在哪里应该进行监听部分,即:

DDS.createListener((topic) -> listen() /* 不知道如何访问 listen 方法 */)

而且,要调用 listen 方法,我需要一个类实例,但我不确定该如何处理。使用 Class.newInstance() 并不合适。我是否需要一种不同的配置?

英文:

I have 3rd party library that uses kafka to abstract pub sub mechanism. I have something like following to subscribe topic

DDS.createListener((topic) -> "do sth with this topic");

I want to take it further and want to create an annotation as follows

@Subscribe("topicName")
public void listen(Topic topic) {
    // do sth with this topic
}

I am having problems when processing annotation.

First, I need to find methods annotated with Subscribe and then need to listen for topics behind the curtain and then when one received, direct it to the annotated method, "listen" in the example case.
Where should I do the listen part which is

DDS.createListener((topic) -> listen() /* dunno how to access listen */)

And also to invoce the listen method, I need a class instance but I am not sure how I am gonna handle that. It does not make sense to do Class.newInstance(). Do I need a different kind of configuration?

答案1

得分: 0

你需要在一个包装类中创建一个 register(Object obj) 方法,该方法用于处理主题注册。这个方法需要在具有 subscribe 方法的类的构造函数中被调用。

因此,无论何时有人调用 register(this) 方法,您将获得对象引用,然后您需要找到带有 @Subscribe 注解的方法,并创建一个监听器,该监听器将使用反射调用给定的方法。

还有其他方法,但这似乎是最简单的方式。

英文:

You need to create register(Object obj) method in a wrapper class which handles your topic registration. This needs to be called in constructor of class where you have subscribe method.

so whenever some one calls register(this) method you will get object reference and you need to find @Subscribe annotated method and create listener which will call given method using reflection.

There other ways but this seems to be easiest

huangapple
  • 本文由 发表于 2020年10月22日 19:39:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/64481452.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定