在 Java 中创建 MBean

2022-09-03 03:18:22

我正在尝试使一个类实现一个 MBean 接口,以便我可以在运行时询问属性。我试图询问的类如下

public class ProfileCache implements ProfileCacheInterfaceMBean{

    private Logger logger = Logger.getLogger(ProfileCache.class);
    private ConcurrentMap<String, Profile> cache;


    public ProfileCache(ConcurrentMap<String, Profile> cache){
        this.cache = cache;     
    }

    /**
     * Update the cache entry for a given user id
     * @param userid the user id to update for 
     * @param profile the new profile to store
     * @return true if the cache update
     */
    public boolean updateCache(String userid, Profile profile) {
        if (cache == null || cache.size() == 0) {
            throw new RuntimeException("Unable to update the cache");
        }
        if (cache.containsKey(userid)) {
            if (profile != null) {
                cache.put(userid, profile);
                logger.info("Updated the cache for user: "
                            + userid + "  profile: " + profile);
                return true;
            }
        }
        return false;
    }

    @Override
    public ConcurrentMap<String, Profile> getCache() {
        if(cache == null){
            cache = new ConcurrentHashMap<String, Profile>();
        }
        return cache;
    }


}

界面看起来像这样

import com.vimba.profile.Profile;

public interface ProfileCacheInterfaceMBean {

    ConcurrentMap<String, Profile> getCache();

}

我像这样启动MBAan

        cacheImpl = new ProfileCache(factory.createCacheFromDB());
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName profileCache = new ObjectName("org.javalobby.tnt.jmx:type=ProfileCacheInterfaceMBean");  
        mbs.registerMBean(cacheImpl, profileCache);

但是,我不断得到以下异常,我不确定我需要更改什么

javax.management.NotCompliantMBeanException: MBean class com.vimba.cache.ProfileCache does not implement DynamicMBean, and neither follows the Standard MBean conventions (javax.management.NotCompliantMBeanException: Class com.vimba.cache.ProfileCache is not a JMX compliant Standard MBean) nor the MXBean conventions (javax.management.NotCompliantMBeanException: com.vimba.cache.ProfileCache: Class com.vimba.cache.ProfileCache is not a JMX compliant MXBean)

我认为可能是因为它返回了地图?


答案 1

刚刚遇到这个例外,并查看了当前的答案以及 https://blogs.oracle.com/jmxetc/entry/javax_management_standardmbean_when_and 我认为强调和澄清以下已经阐明的内容可能会有所帮助:

  1. NotCompliantMBeanException是由于未能遵循此约定而引起的,“ConcreteClassName”实现了“ConcreteClassNameMBean”

  2. 我通过将我的mbean接口的原始名称从“OrignalNameMBean”更新为“OriginalNameMXBean”来解决此问题,从而允许在不遵循约定的情况下注册mbean。

  3. 另一个解决办法是遵守公约。


答案 2

我遇到了同样的问题(“不实现DynamicMBean,也不遵循标准MBean约定”),本文帮助我解决了这个问题(请参阅使用StandardMBean部分:https://blogs.oracle.com/jmxetc/entry/javax_management_standardmbean_when_and)。

我必须显式构造一个

StandardMBean mbean = new StandardMBean(mBeanImpl, MBeanInterface.class);

然后注册 mbean:

mbServer.registerMBean(mbean, mBeanName);

它的工作原理。

当我向 mbServer 注册 mBeanImpl 时,我遇到了上述异常。


推荐