Java 怎么创建MBeanServer

2019年7月18日19:54:37 评论 81

1.简介

Java 怎么创建MBeanServer?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


import java.beans.ConstructorProperties;
import java.util.Date;
import java.lang.management.ManagementFactory;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import javax.management.MBeanServer;
import javax.management.ObjectName;

public class Main {
    
    public static void main(String[] args) throws Exception {
        
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

        
        ObjectName mbeanName = new ObjectName("com.example:type=Hello");

        
        Hello mbean = new Hello();

        
        mbs.registerMBean(mbean, mbeanName);

        
        ObjectName mxbeanName = new ObjectName(
                "com.example:type=QueueSampler");

        
        Queue<String> queue = new ArrayBlockingQueue<String>(10);
        queue.add("Request-1");
        queue.add("Request-2");
        queue.add("Request-3");
        QueueSampler mxbean = new QueueSampler(queue);

        
        mbs.registerMBean(mxbean, mxbeanName);

        
        System.out.println("Waiting for incoming requests...");
        Thread.sleep(Long.MAX_VALUE);
    }
}



 class QueueSample {

    private final Date date;
    private final int size;
    private final String head;

    @ConstructorProperties({ "date", "size", "head" })
    public QueueSample(Date date, int size, String head) {
        this.date = date;
        this.size = size;
        this.head = head;
    }

    public Date getDate() {
        return date;
    }

    public int getSize() {
        return size;
    }

    public String getHead() {
        return head;
    }
}





 class QueueSampler implements QueueSamplerMXBean {

    private Queue<String> queue;

    public QueueSampler(Queue<String> queue) {
        this.queue = queue;
    }

    public QueueSample getQueueSample() {
        synchronized (queue) {
            return new QueueSample(new Date(), queue.size(), queue.peek());
        }
    }

    public void clearQueue() {
        synchronized (queue) {
            queue.clear();
        }
    }
}
interface QueueSamplerMXBean {
    public QueueSample getQueueSample();

    public void clearQueue();
}



 

3.总结

示例代码演示了 Java 怎么创建MBeanServer,具体步骤参见示例代码。

  • A+
所属分类:JMX

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: