Apache Felix Event Admin在ServiceMix容器下使用

2016/06/15 09:10
阅读数 15

1、首先在pom文件中引用

<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.service.event</artifactId>
<version>1.3.1</version>
<type>jar</type>
</dependency>

2、在blueprint文件下引入Event服务,才可以将消息推送到Event里面

<reference id="EventAdmin" interface="org.osgi.service.event.EventAdmin" availability="mandatory"/>

3、将服务注入到Bean里面使用

public class EventAdminUtils{
    private EventAdmin eventAdmin;

    public EventAdmin getEventAdmin() {
        return eventAdmin;
    }

    public void setEventAdmin(EventAdmin eventAdmin) {
        this.eventAdmin = eventAdmin;
    }

    public boolean SyncEvent(String topic, Dictionary props) {
        Event reportGeneratedEvent = new Event(topic,props);
        eventAdmin.sendEvent(reportGeneratedEvent);
        return true;
    }

    public boolean AsyncEvent(String topic, Dictionary props) {
        Event reportGeneratedEvent = new Event(topic,props);
        eventAdmin.postEvent(reportGeneratedEvent);
        return true;
    }

}

blueprint注入服务

<bean id="adminEvent" class="com.test.event.impl.utils">
     <property name="eventAdmin" ref="EventAdmin"/>
</bean>

4、当做一个服务发布出去,需要用到的地方,引用服务就可以

创建一个接口类:

public interface IEventAdminUtils {
    public boolean SyncEvent(String topic,Dictionary props);
    public boolean AsyncEvent(String topic,Dictionary props);
}

创建一个实现类:

public class EventAdminUtils implements IEventAdminUtils{
    private EventAdmin eventAdmin;

    public EventAdmin getEventAdmin() {
        return eventAdmin;
    }

    public void setEventAdmin(EventAdmin eventAdmin) {
        this.eventAdmin = eventAdmin;
    }

    public boolean SyncEvent(String topic, Dictionary props) {
        Event reportGeneratedEvent = new Event(topic,props);
        eventAdmin.sendEvent(reportGeneratedEvent);
        return true;
    }

    public boolean AsyncEvent(String topic, Dictionary props) {
        Event reportGeneratedEvent = new Event(topic,props);
        eventAdmin.postEvent(reportGeneratedEvent);
        return true;
    }

}

blueprint中发布服务

<service ref="Sender" interface="com.test.event.utils.IEventAdminUtils">
    </service>

5、从Event里面拿出内容

public class Handler implements EventHandler {

    @Override
    public void handleEvent(Event event) {
        String reportMsg = (String) event.getProperty("message");
    }
}


展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部