多个路径上的AEM CQ侦听器



我正在尝试使用观察管理器实现事件侦听器。我需要在多个路径上收听。

但是,我相信我们只能在一条路径上注册一个听众。有没有办法在多条路径上监听?

我试过这样的事情

String pathvalues = "path1,path2,path3";
List < String > path = Arrays.asList(pathvalues.split(","));
session = repository.loginAdministrative(repository.getDefaultWorkspace());
observationManager = session.getWorkspace().getObservationManager();
for (String paths: path) {
observationManager.addEventListener(this, Event.NODE_ADDED, paths, true, null, null, false);
}

但这只监听了它迭代的最后一条路径。我想这是有道理的,所以我仍然被困住了。

我在网上找到了这个, SLING-4564

我实现了它,但不知何故它仍然没有听。

如果有人有任何意见,请告诉我。

对于您的第一个问题:

observationManager.addEventListener(this, Event.NODE_ADDED, paths, true, null, null, false);

但这只侦听它迭代的最后一条路径

这是设计使然。偶数侦听器仅注册到一个路径,循环中提供的最后一个路径将是活动路径。最后一次调用addEventListener之前的其他所有内容都将被忽略。

您的问题有两种可能的解决方案:

在父级别注册侦听器,并在调用时筛选事件。

使用eventFilter.setAdditionalPaths(paths);筛选多个路径上的事件,如 SLING-4564 中所述

第一种方法更可取,因为它允许您根据逻辑实现最佳和快速过滤。例如,您的快速过滤器可以是排除/etc/,以便您可以轻松评估事件路径并检查它是否以/etc/开头并丢弃它。

SLING-4564基本上是为大型活动(如OAK启动(而设计的,作为性能的一般准则,特定于应用程序的事件侦听器应限制为特定于应用程序或内容的特定路径,而不是本质上是全局的。

检查以下示例中的 EventConstants.EVENT_FILTER 属性

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingConstants;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
@Component
/**
* The @Component annotation is the only required annotation. If this annotation is not declared for a Java class, the class is
* not declared as a component.
*/
@Service(value = EventHandler.class)
/**
* The @Service annotation defines whether and which service interfaces are provided by the component. This is a class annotation.
* This annotation is used to declare <service> and <provide> elements of the component declaration.
*/
@Properties({
@Property(name = EventConstants.EVENT_TOPIC,
value = { SlingConstants.TOPIC_RESOURCE_ADDED, SlingConstants.TOPIC_RESOURCE_CHANGED, SlingConstants.TOPIC_RESOURCE_REMOVED }),
@Property(name = EventConstants.EVENT_FILTER, value = "(|(path=/content/dam/*/jcr:content)(assetPath=/content/dam/*))") })
public class ExampleServiceImpl implements EventHandler {
final String[] eventProps = { "resourceAddedAttributes", "resourceChangedAttributes", "resourceRemovedAttributes" };
public void handleEvent(org.osgi.service.event.Event event) {
for (String eventProp : eventProps) {
String[] props = (String[]) event.getProperty(eventProp);
}
}
}

最新更新