【问题标题】:Multiple OSGi services多个 OSGi 服务
【发布时间】:2016-04-26 10:08:44
【问题描述】:

我是 OSGi 的新手,正在尝试使用 OSGi 开发应用程序。我有一个 OSGi 服务,它有一个接口和两个实现。

接口:ExportService

实现:ExcelExportServiceImplPdfExportServiceImpl

ExportService 是我的接口,ExcelExportServiceImplPdfExportServiceImplExportService 的实现。

我希望 ExcelExportServiceImplPdfExportServiceImpl 作为两个不同的服务。

从我的应用程序包中,如果我想使用 excel 导出,我应该能够调用ExcelExportServiceImpl 服务而不涉及PdfExportServiceImpl

如何注册两个具有相同接口的不同服务?

@Override
public void start(BundleContext context) throws Exception {
        context.registerService(ExportService.class.getName(), new ExcelExportServiceImpl(), null);
        context.registerService(ExportService.class.getName(), new PdfExportServiceImpl(), null);
    }
}

现在,我在我的激活器中提出了上面的代码,但它似乎不起作用,因为这两个服务都有 ExportService.class.getName() 作为类名。如何通过一个接口实现同一个bundle中的两种不同服务?

更新/解决方案:

我在服务包的激活器中更改了如下代码,

@Override
public void start(BundleContext context) throws Exception {
        Hashtable excelProperty = new Hashtable();
        excelProperty.put("type", "excel");
        excelServiceRegistration = context.registerService(ExportService.class.getName(), new ExcelExportServiceImpl(), excelProperty);
        Hashtable pdfProperty = new Hashtable();
        pdfProperty.put("type", "pdf");
        pdfServiceRegistration = context.registerService(ExportService.class.getName(), new PdfExportServiceImpl(), pdfProperty);
}

在我的应用程序包中,我添加了以下过滤器

public static void startBundle(BundleContext context) throws InvalidSyntaxException {
    String EXCEL_FILTER_STRING = "(&(" + Constants.OBJECTCLASS + "=com.stpl.excel.api.ExportService)" + "(type=excel))";
    String PDF_FILTER_STRING = "(&(" + Constants.OBJECTCLASS + "=com.stpl.excel.api.ExportService)" + "(type=pdf))";
    Filter excelFilter = context.createFilter(EXCEL_FILTER_STRING);
    Filter pdfFilter = context.createFilter(PDF_FILTER_STRING);
    ServiceTracker excelService = new ServiceTracker(context, excelFilter, null);
    ServiceTracker pdfService = new ServiceTracker(context, pdfFilter, null);
    excelService.open();
    pdfService.open();
}

【问题讨论】:

    标签: java service osgi osgi-bundle


    【解决方案1】:

    上面的代码将使用相同的接口注册两个不同的服务。这是正确的。

    问题是通过接口绑定服务的消费者会得到这些服务之一,无法决定哪个是正确的。

    解决此问题的一种方法是向每个服务注册添加属性。例如,您可能在 pdf 上设置了一个 proerty type=pdf。

    然后客户端可以通过接口和像 (type=pdf) 这样的 ldap 过滤器来绑定服务。然后它将只匹配 pdf ExportService 服务。

    【讨论】:

    • 有没有办法获得服务接口的所有实现者的句柄?
    • ServiceTracker 始终跟踪所有匹配的服务。您可以使用 getServices 来获取所有实现。一般来说,虽然使用普通的 OSGi API 很难做到正确。因此,您还应该看看您的应用程序的声明式服务。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 2015-07-20
    • 2010-10-20
    • 2014-09-26
    • 1970-01-01
    相关资源
    最近更新 更多