idea搭建osgi项目开发学习

83次阅读

共计 2401 个字符,预计需要花费 7 分钟才能阅读完成。

本文介绍了在 mac 系统上如何用 idea 搭建 osgi 项目开发,演示使用的 equinor osgi framework,jdk8。

equinor 下载

下载地址:https://download.eclipse.org/…
本文下载的是 equinox-SDK-4.11.zip,下载后进行解压,后面需要用到这个解压目录。

idea 创建工程

File -> New -> Project,选择 Java,点击 Next,创建一个空工程。

继续点击 Next。

填写项目名称,这里叫 osgi_demo。

工程下创建 osgi 模块

创建 api、server、client 三个模块。
创建模块时勾选 OSGI 作为开发环境,Use library 从刚才下载的 equinox 解压的目录下的 plugins 目录中选择 org.eclipse.osgi_3.13.300.v20190218-1622.jar。

创建模块完成之后,打开 idea 的 preferences,在 Languages & Frameworks 找到 OSGI Framework Instances 选项。

添加 Equinox,Home directory 选择刚才解压的 Equinox 目录。

编写演示代码

结构如下图

api 模块中定义接口类 IHelloService

package osgi.demo.api;

public interface IHelloService {
    /**
     * 和某人打招呼
     * @param somebody
     * @return
     */
    String sayHello(String somebody);
}

server 模块接口实现类 HelloServiceImpl

package osgi.demo.server;

import osgi.demo.api.IHelloService;

public class HelloServiceImpl implements IHelloService {
    @Override
    public String sayHello(String somebody) {return "hello" + somebody;}
}

server 模块服务注册类 HelloServerBundle

package osgi.demo.server;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import osgi.demo.api.IHelloService;

import java.util.Dictionary;
import java.util.Hashtable;

public class HelloServerBundle implements BundleActivator {
    @Override
    public void start(BundleContext bundleContext) throws Exception {IHelloService service = new HelloServiceImpl();
        Dictionary<String , Object> properties = new Hashtable<>();
        // 服务注册
        bundleContext.registerService(IHelloService.class, service, properties);
    }

    @Override
    public void stop(BundleContext bundleContext) throws Exception {}}

client 模块调用服务类 HelloClientBundle

package osgi.demo.client;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import osgi.demo.api.IHelloService;

import java.util.Objects;

public class HelloClientBundle implements BundleActivator {
    @Override
    public void start(BundleContext bundleContext) throws Exception {
        // 获取到 IHelloService 服务引用
        ServiceReference<IHelloService> reference = bundleContext.getServiceReference(IHelloService.class);
        if (Objects.nonNull(reference)) {
            // 发现服务
            IHelloService service = bundleContext.getService(reference);
            if (Objects.nonNull(service)) {System.out.println(service.sayHello("jecyhw"));
            }
            // 注销服务
            bundleContext.ungetService(reference);
        }
    }

    @Override
    public void stop(BundleContext bundleContext) throws Exception {}}

各模块 osgi 配置

api 模块配置,导出接口定义所在包 osgi.demo.api。

VZD)
server 模块配置,配置 HelloServerBundle 类作为该 bundle 的启动类。

client 模块配置,配置 HelloClientBundle 类作为该 bundle 的启动类。

osgi 启动配置并运行

选择 Edit Configurations。

添加 OSGI Bundles。

配置如下。

点击 OK 之后,就可以运行了。

运行结果截图。

正文完
 0