Pergunta

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

Foi útil?

Solução

You need to register each MBean with a unique name. If you do that you will no longer receive the exception when registering the second MBean. You will have to manage each bean separately (i.e. the attribute on each Home object is set through individual MBeans).

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"));

If you want to manage the two Hello objects at the same time through one MBean, (i.e change attribute on one MBean results in the change on both Hello objects) you could try using a Composite Hello object and expose that as an MBean.

Common interface:

interface IHello {
    void setAttribute(int value);
}

Single hello object:

class Hello implements IHello {
    int attribute;

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

Composite hello object:

class CompositeHello implements IHello {
    IHello[] Hellos;

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

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

Register composite 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"));
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top