2

I want to register more than one MBean of same class.

I have Hello class implementing the HelloMBean interface.

Now in main i have two object of Hello class and I want to register them both

MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName("mBeans:type=Hello");

Hello h1 = new Hello();
Hello h2 = new Hello();

mbs.registerMBean(h1, name);
mbs.registerMBean(h2, name);

This throws InstanceAlreadyExistsException .

How can I register both h1 and h2, and using jConsole view both of them?


Reason of this,

I want to change the attribute value of both h1 and h2 object through MBean

4

1 回答 1

2

您需要为每个 MBean 注册一个唯一的名称。如果您这样做,则在注册第二个 MBean 时将不再收到异常。您必须分别管理每个 bean(即每个 Home 对象的属性是通过单独的 MBean 设置的)。

MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

Hello h1 = new Hello();
Hello h2 = new Hello();

mbs.registerMBean(h1, new ObjectName("mBeans:type=Hello-1"));
mbs.registerMBean(h2, new ObjectName("mBeans:type=Hello-2"));

如果您想Hello通过一个 MBean 同时管理两个对象(即更改一个 MBean 上的属性会导致两个 Hello 对象上的更改),您可以尝试使用复合Hello 对象并将其公开为 MBean。

通用接口:

interface IHello {
    void setAttribute(int value);
}

单个 hello 对象:

class Hello implements IHello {
    int attribute;

    void setAttribute(int value) {
        attribute = value;
    }
}

复合 hello 对象:

class CompositeHello implements IHello {
    IHello[] Hellos;

    CompositeHome(IHello...hellos) {
        super();
        this.hellos = hellos;
    }

    void setAttribute(int value) {
        for (IHello hello : hello) {
            home.setAttribute(value);
        }
    }
}

注册复合 MBean:

MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

Hello h1 = new Hello();
Hello h2 = new Hello();
CompositeHello composite = new CompositeHello(h1, h2);
mbs.registerMBean(composite, new ObjectName("mBeans:type=Hello"));
于 2013-04-25T18:57:24.953 回答