本文介绍了在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之后,就可以运行了。

运行结果截图。