9.2. 標準の MBean の例
ここでは、サービスアーカイブ (
.sar) で一緒にパッケージ化される 2 つの MBean サービスのサンプルを開発します。
ConfigServiceMBean インターフェイスは、次のような特定のメソッドを宣言します。start、getTimeoutとstopJBoss 固有のクラスを使用せずに、MBean を正しく 開始、保持、および 停止 するためのメソッド。ConfigService クラスは ConfigServiceMBean インターフェースを実装した後、このインターフェース内で使用されたメソッドを実装します。
PlainThread クラスは ServiceMBeanSupport クラスを拡張し、PlainThreadMBean インターフェイスを実装します。PlainThread はスレッドを開始し、ConfigServiceMBean.getTimeout()スレッドがスリープする時間を決定します。
例9.1 サンプル MBean サービス
package org.jboss.example.mbean.support;
public interface ConfigServiceMBean {
int getTimeout();
void start();
void stop();
}
package org.jboss.example.mbean.support;
public class ConfigService implements ConfigServiceMBean {
int timeout;
@Override
public int getTimeout() {
return timeout;
}
@Override
public void start() {
//Create a random number between 3000 and 6000 milliseconds
timeout = (int)Math.round(Math.random() * 3000) + 3000;
System.out.println("Random timeout set to " + timeout + " seconds");
}
@Override
public void stop() {
timeout = 0;
}
}
package org.jboss.example.mbean.support;
import org.jboss.system.ServiceMBean;
public interface PlainThreadMBean extends ServiceMBean {
void setConfigService(ConfigServiceMBean configServiceMBean);
}
package org.jboss.example.mbean.support;
import org.jboss.system.ServiceMBeanSupport;
public class PlainThread extends ServiceMBeanSupport implements PlainThreadMBean {
private ConfigServiceMBean configService;
private Thread thread;
private volatile boolean done;
@Override
public void setConfigService(ConfigServiceMBean configService) {
this.configService = configService;
}
@Override
protected void startService() throws Exception {
System.out.println("Starting Plain Thread MBean");
done = false;
thread = new Thread(new Runnable() {
@Override
public void run() {
try {
while (!done) {
System.out.println("Sleeping....");
Thread.sleep(configService.getTimeout());
System.out.println("Slept!");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
thread.start();
}
@Override
protected void stopService() throws Exception {
System.out.println("Stopping Plain Thread MBean");
done = true;
}
}
jboss-service.xml 記述子は、イン ジェクト タグを使用して ConfigService クラスが PlainThread クラスにインジェクトされる方法を示します。inject タグは PlainThreadMBean と ConfigServiceMBean 間の依存関係を確立し、PlainThreadMBean が簡単に ConfigServiceMBean を使用できるようにします。
例9.2 JBoss-service.xml サービス記述子
<server xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:jboss:service:7.0 jboss-service_7_0.xsd"
xmlns="urn:jboss:service:7.0">
<mbean code="org.jboss.example.mbean.support.ConfigService" name="jboss.support:name=ConfigBean"/>
<mbean code="org.jboss.example.mbean.support.PlainThread" name="jboss.support:name=ThreadBean">
<attribute name="configService">
<inject bean="jboss.support:name=ConfigBean"/>
</attribute>
</mbean>
</server>
MBean のサンプルを記述した後、クラスと
jboss-service.xml 記述子をサービスアーカイブ (.sar) の META-INF/ フォルダーでパッケージ化できます。