`

DS(声明式服务)的应用

阅读更多

Declarative Services 定义

Declarative Services 是一个面向服务的组件模型,它制订的目的是更方便地在 OSGi 服务平台上发布、查找、绑定服务,对服务进行动态管理,如监控服务状态以及解决服务之间的复杂的依赖关系等问题。Declarative Services 采用服务组件的延迟加载以及组件生命周期管理的方式来控制对于内存的占用以及启动的快速,很好的解决了传统的 OSGi 服务模型在开发和部署比较复杂应用时内存占用大、启动慢等问题,并且对服务组件的描述采用XML来实现,十分便于用户理解和使用。 

 

1、 定义服务

    获取 [r1] OSGi的一个eclipse实现。

    在sample.http插件中,编写一个接口UserService, 并把它的package包export暴露给其他插件。

 

2、 服务组件Component

  1> 使用事件策略(像依赖注入的set方式)

    (1)新建Helper类,作为服务组件实现;

public class UserHelper {

	public UserHelper() {
	}

	private static UserHelper INSTANCE;

	public static UserHelper getInstance() {
		return INSTANCE;
	}

	protected void activate() {
		System.out.println("activate "  + this);
		INSTANCE = this;
	}

	protected void deactivate() {
		System.out.println("deactivate "  + this);
		INSTANCE = null;
	}

	private UserService service;

	public UserService getService() {
		return service;
	}

	protected void setService(UserService manager) {
		System.out.println("register user-service : " + manager);
		this.service = manager;
	}

	protected void unSetService(UserService manager) {
		System.out.println("unregister user-service : " + manager);
		this.service = null;
	}

}

 

    (2)添加org.eclipse.equinox.ds插件的依赖;

    (3)在OSGI-INF目录下新建组件New->Plug-in Development->Component Defintion。在MANIFEST.MF中添加Service-Component 属性,指定该 Bundle 应用的服务组件配置文件;

    reference参数含义请查看这里

 

    2> 使用lookup策略,在上下文中通过name获得服务。

 

3、 绑定(实现)服务

   (1) 新建插件sample.http.user.en插件,然后添加sample.http和org.eclipse.equinox.ds的依赖;

   (2) 实现UserService接口。

   (3) 新建Component Defintion,绑定到服务。

 

4、 测试

运行/sample.server/server-web.product,打开浏览器http://localhost/helloworld?username=test

 

源码:

[r1]简单的OSGi :https://github.com/winse/hello/tree/ca902237e03c05f13c7a3cf838de48c825d98dc4

[r2]实现后的DS版本: https://github.com/winse/hello/tree/5ffea88d723bae34099d6c94686436dc8fd2eb28

 

参考资料:

1: 利用 Eclipse 开发基于 OSGi 的 Bundle 应用(使用代码注册服务)

http://www.ibm.com/developerworks/cn/opensource/os-ecl-osgibdev/index.html

2: OSGi 中的 Declarative Services 规范简介

http://www.ibm.com/developerworks/cn/opensource/os-ecl-osgids/index.html

3: Getting Started with OSGi: Declarative Services and Dependencies (这一篇文章太正了!同时是一篇CommandProvider的实现)

http://www.eclipsezone.com/eclipse/forums/t97690.rhtml

4: Getting Started with OSGi: Introducing Declarative Services

http://www.eclipsezone.com/eclipse/forums/t96740.html

5: Declarative Services规范简介及应用

http://marsvaadin.iteye.com/blog/1678286

6: OSGi 中的 Declarative Services 规范简介

http://www.ibm.com/developerworks/cn/opensource/os-ecl-osgids/index.html

  • 大小: 33.4 KB
  • 大小: 49.9 KB
  • 大小: 59 KB
  • 大小: 59.4 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics