如何从服务中取消注册OSGI /蓝图服务?

时间:2012-08-16 09:24:54

标签: osgi blueprint-osgi

在我的应用程序中,我有一个Service ChatProtocolClient。该实现是一个tcp客户端,它在蓝图“init-method”中连接到远程服务器,并在“destroy-method”中断开连接。

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

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

然后,Blueprint会自动在所有依赖bean(Blueprint注入此服务引用的bean)上调用destroy-method,并初始化一个新的ChatProtocolClient bean以及因依赖失败而被销毁的所有bean。

如何做到这一点?

1 个答案:

答案 0 :(得分:0)

我找到了实现这个目标的方法。在此解决方案中,蓝图不是重新创建所有相关服务的实例。它是这样的:

  1. 连接“看门狗”豆。
  2. 我没有创建“ChatProtocolClient”Bean,而是从xml创建了ConnectionWatchDog bean。在这些bean中,将注入BundleContext,并从.xml文件设置连接属性。 然后,ConnectionWatchDog尝试创建/连接ChatProtocolClient实例。如果连接成功,它会在BundleContext中注册一个服务(使用bundleContext.registerService(..))。 ServiceRegistration保存在监视程序中。看门狗在设置的时间间隔内测试连接(它运行它自己的线程)。如果连接似乎失败了;看门狗调用serviceRegistration.unregister()并清理客户端连接实例的剩余部分,并启动创建,连接和注册新的ChatProtocolClient实例的整个过程。

    1. ChatChannel
    2. 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>
      

      设置为service-object的成员类型意味着当注册或取消注册服务时,将使用“onBind”和“onUnbind”方法通知ChatChannel。作为参数,他们将获得一个ChatProtocolClientInterface实例。

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