如何从服务中注销OSGI/Blueprint服务?

如何从服务中注销OSGI/Blueprint服务?,osgi,blueprint-osgi,Osgi,Blueprint Osgi,在我的应用程序中,我有一个服务聊天协议客户端。该实现是一个tcp客户端,它在蓝图“init方法”中连接到远程服务器,并在“destroy方法”中断开连接 我还有另一个包,它使用这个ChatProtocolClient的连接从一个频道ChatChannel读取和发布消息。 目前,我有一个xml文件,它创建了ChatProtocolClient的一个bean,并创建了一个bean ChatChannel,其中注入了对已创建ChatProtocolClient服务的引用 但我如何处理与服务器的断开连接

在我的应用程序中,我有一个服务聊天协议客户端。该实现是一个tcp客户端,它在蓝图“init方法”中连接到远程服务器,并在“destroy方法”中断开连接

我还有另一个包,它使用这个ChatProtocolClient的连接从一个频道ChatChannel读取和发布消息。 目前,我有一个xml文件,它创建了ChatProtocolClient的一个bean,并创建了一个bean ChatChannel,其中注入了对已创建ChatProtocolClient服务的引用

但我如何处理与服务器的断开连接?我想告诉Blueprint框架我的ChatProtocolClient实例现在不可用,它应该注销这个实例

最好Blueprint会自动调用所有依赖bean(Blueprint在其中注入此服务引用的bean)上的destroy方法,并初始化一个新的ChatProtocolClient bean和所有由于依赖失败而被销毁的bean


如何做到这一点?

我找到了实现这一点的方法。在此解决方案中,不是Blueprint重新创建所有依赖服务的实例。事情是这样的:

<blueprint xmlns=...>
    <reference-list id="chat-connection" member-type="service-object" interface="com.example.ChatProtocolClientInterface">
      <reference-listener bind-method="onBind" unbind-method="onUnbind" ref="Channel1"/>
    </reference-list>
    <bean id="Channel1" class="ChatChannel" init-method="startUp">
       <property name="chatProtocolClient" ref="chat-connection">
       ... some other properties ...
    </bean>
</blueprint>
  • 连接“看门狗”bean
  • 我没有创建“ChatProtocolClient”bean,而是从xml创建了ConnectionWatchDog bean。在这些bean中,BundleContext被注入,连接属性从.xml文件设置。 然后ConnectionWatchDog尝试创建/连接ChatProtocolClient实例。如果连接成功,它将在BundleContext中注册服务(使用BundleContext.registerService(..)。服务注册保存在看门狗中。看门狗在设置的时间间隔内测试连接(它运行自己的线程)。如果连接出现故障;看门狗调用serviceRegistration.unregister()并清理客户端连接实例的剩余部分,并启动创建、连接和注册新ChatProtocolClient实例的整个过程

  • 聊天频道
  • ChatChannel现在在Blueprint中配置为一个。xml如下所示:

    <blueprint xmlns=...>
        <reference-list id="chat-connection" member-type="service-object" interface="com.example.ChatProtocolClientInterface">
          <reference-listener bind-method="onBind" unbind-method="onUnbind" ref="Channel1"/>
        </reference-list>
        <bean id="Channel1" class="ChatChannel" init-method="startUp">
           <property name="chatProtocolClient" ref="chat-connection">
           ... some other properties ...
        </bean>
    </blueprint>
    
    
    ... 其他一些属性。。。
    
    设置为服务对象的成员类型意味着,当服务注册或取消注册时,将使用“onBind”和“onUnbind”方法通知ChatChannel。作为参数,它们将获得一个ChatProtocolClientInterface实例

    我不确定这是唯一的还是最好的解决方案,但它对我有效。注意,对于这个示例xml,您还需要一个“chatProtocolClient”的setter;目前我不使用blueprint设置的列表,我只使用onBind和onUnbind方法