我是OSGi技术的新手,我在使用Event时遇到问题。我的应用程序一直等到下午6:00,服务器捆绑包会向客户端捆绑包发送一条消息。因此,我进行了一些研究,发现可以使用EventAdmin来完成:
注意:如果可能有一个代码示例,我将很高兴。
谢谢
最佳答案
您可以找到以下示例
制片人:
https://github.com/robertcsakany/welcometoosgi/tree/master/hu.blackbelt.welcometoosgi.eventproducer
import org.apache.felix.scr.annotations.*;
import org.apache.felix.scr.annotations.Component;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Dictionary;
import java.util.Hashtable;
@Component(metatype = true, immediate = true)
@Properties(value = {
@Property(name = "fooBar", value = "bar")
})
public class EventProducer {
Logger log = LoggerFactory.getLogger(EventProducer.class);
private String foo = "";
@Reference
EventAdmin eventAdmin;
@Activate
public void activate(ComponentContext context) {
Dictionary properties = new Hashtable();
properties.put("test", context.getProperties().get("fooBar"));
Event generatedEvent = new Event("test/event/GENERATED", properties);
log.info("Sending event");
eventAdmin.sendEvent(generatedEvent);
}
}
对于消费者:
https://github.com/robertcsakany/welcometoosgi/tree/master/hu.blackbelt.welcometoosgi.eventconsumer
import org.apache.felix.scr.annotations.*;
import org.apache.felix.scr.annotations.Component;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(metatype = true, immediate = true)
@Service
@Properties(value = {
@Property(name = EventConstants.EVENT_TOPIC, value = {"test/event/GENERATED"})
})
public class EventConsumer implements EventHandler {
Logger log = LoggerFactory.getLogger(EventConsumer.class);
private String foo = "";
@Override
public void handleEvent(Event event) {
log.info("Event catched - "+event.getTopic());
log.info("Event property - "+event.getProperty("test"));
}
}
那就是使用声明式服务从服务跟踪器引用其他服务