osgi实战学习之路:5.生命周期及利用命令、装饰者模式实现基于socket交互Bundle命令demo

时间:2022-05-30 16:58:05

生命周期中关键3个类:


BundleActivator

入口点,类似main方法

BundleContext

Bundle上下文对象,在执行期间,为应用程序提供操作osgi框架的方法

Bundle

代表一个已安装的Bundle

接口说明:


BundleActivator:

public interface BundleActivator {
public void start(BundleContext context) throws Exception;
public void stop(BundleContext context) throws Exception;
}

BundleContext:

public interface BundleContext {
...
String getProperty(String key);
Bundle getBundle();
Bundle installBundle(String location, InputStream input)
throws BundleException;
Bundle installBundle(String location) throws BundleException;
Bundle getBundle(long id);
Bundle[] getBundles();
void addBundleListener(BundleListener listener);
void removeBundleListener(BundleListener listener);
void addFrameworkListener(FrameworkListener listener);
void removeFrameworkListener(FrameworkListener listener);
...
}

Bundle:

...
BundleContext getBundleContext();
long getBundleId();
Dictionary getHeaders();
Dictionary getHeaders(String locale);
String getLocation();
int getState();
String getSymbolicName();
Version getVersion();
void start(int options) throws BundleException;
void start() throws BundleException;
void stop(int options) throws BundleException;
void stop() throws BundleException;
void update(InputStream input) throws BundleException;
void update() throws BundleException;
void uninstall() throws BundleException;

Bundle状态图:


osgi实战学习之路:5.生命周期及利用命令、装饰者模式实现基于socket交互Bundle命令demo

源码下载


demo:

准备:

在karaf_home下新建config、logs目录

将my-shell下的server.properties拷贝到karaf_home/config下

增加log4j日志配置,參考

部署Bundle

bundle:install -s mvn:com.demo.shell/my-shell/1.0.0-SNAPSHOT

打开window命令行输入:

telnet localhost 7080

输入help,能够查看全部命令帮助

输入install命令,部署外部Bundle:

install http://localhost:9090/testweb/bundle/user-model-0.0.1-SNAPSHOT.jar

在karaf中输入list,能够查看已经部署的bundle id

在window命令行输入命令,启动bundle

start bundle_id

在karaf中输入list,查看已部署的Bundle处于Active状态