Apache Karaf自定义console命令

测试环境

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的话,需要手工注入

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值