测试环境
Apache karaf 2.4.3 (Apache servicemix 5.5.0)
有2种方法
方法一:
1:添加maven依赖
<dependency>
<groupId>org.apache.karaf.shell</groupId>
<artifactId>org.apache.karaf.shell.console</artifactId>
<version>2.4.3</version>
</dependency>
2:写一个类,继承org.apache.karaf.shell.console.OsgiCommandSupport,然后重写doExecute即可
package com.lala.command;
import org.apache.karaf.shell.console.OsgiCommandSupport;
public class RPCList extends OsgiCommandSupport
{
protected Object doExecute() throws Exception
{
System.out.println("rpc list");
System.out.println(this.bundleContext.getBundle().getSymbolicName());
return null;
}
}
3:在blueprint.xml里面配置
<command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.0.0">
<command name="rpc/list">
<action class="com.lala.command.RPCList" />
</command>
</command-bundle>
部署之后,就可以使用rpc:list命令了
方法二:通过发布服务的方式
1:直接写一个类,方法的参数,就是执行命令的参数
package com.lala.command;
import org.osgi.framework.BundleContext;
public class RPCCommand
{
protected BundleContext bundleContext;
public void add(String a, String b)
{
System.out.println("===============add==============");
System.out.println(a + "\t" + b);
}
public void div(int a, int b)
{
System.out.println("===============div==============");
System.out.println(a + b);
}
public void test()
{
System.out.println("===============test==============");
System.out.println(bundleContext.getBundle().getSymbolicName());
}
public void setBundleContext(BundleContext bundleContext)
{
this.bundleContext = bundleContext;
}
}
2:在blueprint.xml里面发布一个服务
<service auto-export="all-classes">
<service-properties>
<entry key="osgi.command.scope" value="calc" />
<entry key="osgi.command.function">
<array value-type="java.lang.String">
<value>add</value>
<value>div</value>
<value>test</value>
</array>
</entry>
</service-properties>
<bean class="com.lala.command.RPCCommand">
<property name="bundleContext" ref="blueprintBundleContext" />
</bean>
</service>
这里配置了三个命令,对应的上面的三个方法
部署之后,就可以使用如下命令了
calc:add arg0 arg1
calc:dev arg0 arg1
calc:test
第一种方式不需要注入bundleContext,直接使用,但是,需要依赖karaf的api
第二种方式没什么依赖,如果需要使用bundleContext的话,需要手工注入