下面列出了怎么用javax.management.remote.JMXConnectorFactory的API类实例代码及写法,或者点击链接到github查看源代码。
private static void connect(String pid, String address) throws Exception {
if (address == null) {
throw new RuntimeException("Local connector address for " +
pid + " is null");
}
System.out.println("Connect to process " + pid + " via: " + address);
JMXServiceURL url = new JMXServiceURL(address);
JMXConnector c = JMXConnectorFactory.connect(url);
MBeanServerConnection server = c.getMBeanServerConnection();
System.out.println("Connected.");
RuntimeMXBean rt = newPlatformMXBeanProxy(server,
RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
System.out.println(rt.getName());
// close the connection
c.close();
}
private MBeanInfo testMBeanForDatasource() throws Exception {
Map<String, String[]> env = new HashMap<>();
String[] credentials = { "admin", "admin" };
env.put(JMXConnector.CREDENTIALS, credentials);
try {
String url = "service:jmx:rmi://localhost:12311/jndi/rmi://localhost:11199/jmxrmi";
JMXServiceURL jmxUrl = new JMXServiceURL(url);
JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxUrl, env);
MBeanServerConnection mBeanServer = jmxConnector.getMBeanServerConnection();
ObjectName mbeanObject = new ObjectName(dataSourceName + ",-1234:type=DataSource");
MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(mbeanObject);
return mBeanInfo;
} catch (MalformedURLException | MalformedObjectNameException | IntrospectionException | ReflectionException e) {
throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
}
}
private static void dotest(JMXServiceURL url, MBeanServer mbs)
throws Exception {
JMXConnectorServer server = null;
JMXConnector client = null;
server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
server.start();
JMXServiceURL outputAddr = server.getAddress();
System.out.println("Server started ["+ outputAddr+ "]");
client = JMXConnectorFactory.newJMXConnector(outputAddr, null);
client.connect();
System.out.println("Client connected");
MBeanServerConnection connection
= client.getMBeanServerConnection();
System.out.println(connection.getDefaultDomain());
}
private static void dotest(JMXServiceURL url, MBeanServer mbs)
throws Exception {
JMXConnectorServer server = null;
JMXConnector client = null;
server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
server.start();
JMXServiceURL outputAddr = server.getAddress();
System.out.println("Server started ["+ outputAddr+ "]");
client = JMXConnectorFactory.newJMXConnector(outputAddr, null);
client.connect();
System.out.println("Client connected");
MBeanServerConnection connection
= client.getMBeanServerConnection();
System.out.println(connection.getDefaultDomain());
}
private static void connect(String pid, String address) throws Exception {
if (address == null) {
throw new RuntimeException("Local connector address for " +
pid + " is null");
}
System.out.println("Connect to process " + pid + " via: " + address);
JMXServiceURL url = new JMXServiceURL(address);
JMXConnector c = JMXConnectorFactory.connect(url);
MBeanServerConnection server = c.getMBeanServerConnection();
System.out.println("Connected.");
RuntimeMXBean rt = newPlatformMXBeanProxy(server,
RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
System.out.println(rt.getName());
// close the connection
c.close();
}
public static void main(String[] args) throws Exception {
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
Sender sender = new Sender();
mbs.registerMBean(sender, testObjectName);
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
JMXConnector cc = JMXConnectorFactory.connect(addr);
try {
test(mbs, cs, cc);
} finally {
cc.close();
cs.stop();
}
}
public MBeanServerConnection getMBeanServerConnection(String user,
String password) throws Exception {
HashMap<String,String[]> env = new HashMap<String,String[]>();
if (user != null) {
String[] credentials = new String[] {
user, password };
env.put("jmx.remote.credentials", credentials);
}
JMXConnector jmxc = JMXConnectorFactory.connect(url, env);
MBeanServerConnection jmxConn = jmxc.getMBeanServerConnection();
Map<MBeanServerConnection,JMXConnector> conns = connections.get();
if (conns == null) {
conns = new HashMap<MBeanServerConnection,JMXConnector>();
connections.set(conns);
}
conns.put(jmxConn, jmxc);
return jmxConn;
}
private static void tryConnect(int port, boolean shouldSucceed) throws Exception {
String jmxUrlStr =
String.format(
"service:jmx:rmi:///jndi/rmi://localhost:%d/jmxrmi",
port);
JMXServiceURL url = new JMXServiceURL(jmxUrlStr);
HashMap<String, ?> env = new HashMap<>();
boolean succeeded;
try {
JMXConnector c = JMXConnectorFactory.connect(url, env);
c.getMBeanServerConnection();
succeeded = true;
} catch(Exception ex) {
succeeded = false;
}
if (succeeded && !shouldSucceed) {
throw new Exception("Could connect to agent, but should not have been possible");
}
if (!succeeded && shouldSucceed) {
throw new Exception("Could not connect to agent");
}
}
private static void connect(String pid, String address) throws Exception {
if (address == null) {
throw new RuntimeException("Local connector address for " +
pid + " is null");
}
System.out.println("Connect to process " + pid + " via: " + address);
JMXServiceURL url = new JMXServiceURL(address);
JMXConnector c = JMXConnectorFactory.connect(url);
MBeanServerConnection server = c.getMBeanServerConnection();
System.out.println("Connected.");
RuntimeMXBean rt = newPlatformMXBeanProxy(server,
RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
System.out.println(rt.getName());
// close the connection
c.close();
}
private static void connect(String pid, String address) throws Exception {
if (address == null) {
throw new RuntimeException("Local connector address for " +
pid + " is null");
}
System.out.println("Connect to process " + pid + " via: " + address);
JMXServiceURL url = new JMXServiceURL(address);
JMXConnector c = JMXConnectorFactory.connect(url);
MBeanServerConnection server = c.getMBeanServerConnection();
System.out.println("Connected.");
RuntimeMXBean rt = newPlatformMXBeanProxy(server,
RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
System.out.println(rt.getName());
// close the connection
c.close();
}
public static void main(String[] args) throws Exception {
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
Sender sender = new Sender();
mbs.registerMBean(sender, testObjectName);
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
JMXConnector cc = JMXConnectorFactory.connect(addr);
try {
test(mbs, cs, cc);
} finally {
cc.close();
cs.stop();
}
}
/**
* Instantiates a new JMXExecutor targeting the VM indicated by the given host/port combination or a full JMX
* Service URL
*
* @param target a host/port combination on the format "host:port" or a full JMX Service URL of the target VM
*/
public JMXExecutor(String target) {
String urlStr;
if (target.matches("^\\w[\\w\\-]*(\\.[\\w\\-]+)*:\\d+$")) {
/* Matches "hostname:port" */
urlStr = String.format("service:jmx:rmi:///jndi/rmi://%s/jmxrmi", target);
} else if (target.startsWith("service:")) {
urlStr = target;
} else {
throw new IllegalArgumentException("Could not recognize target string: " + target);
}
try {
JMXServiceURL url = new JMXServiceURL(urlStr);
JMXConnector c = JMXConnectorFactory.connect(url, new HashMap<>());
mbs = c.getMBeanServerConnection();
} catch (IOException e) {
throw new CommandExecutorException("Could not initiate connection to target: " + target, e);
}
}
private static void connect(String pid, String address) throws Exception {
if (address == null) {
throw new RuntimeException("Local connector address for " +
pid + " is null");
}
System.out.println("Connect to process " + pid + " via: " + address);
JMXServiceURL url = new JMXServiceURL(address);
JMXConnector c = JMXConnectorFactory.connect(url);
MBeanServerConnection server = c.getMBeanServerConnection();
System.out.println("Connected.");
RuntimeMXBean rt = newPlatformMXBeanProxy(server,
RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
System.out.println(rt.getName());
// close the connection
c.close();
}
private static void tryConnect(int port, boolean shouldSucceed) throws Exception {
String jmxUrlStr =
String.format(
"service:jmx:rmi:///jndi/rmi://localhost:%d/jmxrmi",
port);
JMXServiceURL url = new JMXServiceURL(jmxUrlStr);
HashMap<String, ?> env = new HashMap<>();
boolean succeeded;
try {
JMXConnector c = JMXConnectorFactory.connect(url, env);
c.getMBeanServerConnection();
succeeded = true;
} catch(Exception ex) {
succeeded = false;
}
if (succeeded && !shouldSucceed) {
throw new Exception("Could connect to agent, but should not have been possible");
}
if (!succeeded && shouldSucceed) {
throw new Exception("Could not connect to agent");
}
}
private MBeanInfo testMBeanForDatasource() throws Exception {
Map<String, String[]> env = new HashMap<>();
String[] credentials = { "admin", "admin" };
env.put(JMXConnector.CREDENTIALS, credentials);
try {
String url = "service:jmx:rmi://localhost:12311/jndi/rmi://localhost:11199/jmxrmi";
JMXServiceURL jmxUrl = new JMXServiceURL(url);
JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxUrl, env);
MBeanServerConnection mBeanServer = jmxConnector.getMBeanServerConnection();
ObjectName mbeanObject = new ObjectName(dataSourceName + ",-1234:type=DataSource");
MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(mbeanObject);
return mBeanInfo;
} catch (MalformedURLException | MalformedObjectNameException | IntrospectionException |
ReflectionException e) {
throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
}
}
private static void connect(String pid, String address) throws Exception {
if (address == null) {
throw new RuntimeException("Local connector address for " +
pid + " is null");
}
System.out.println("Connect to process " + pid + " via: " + address);
JMXServiceURL url = new JMXServiceURL(address);
JMXConnector c = JMXConnectorFactory.connect(url);
MBeanServerConnection server = c.getMBeanServerConnection();
System.out.println("Connected.");
RuntimeMXBean rt = newPlatformMXBeanProxy(server,
RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
System.out.println(rt.getName());
// close the connection
c.close();
}
private static void tryConnect(int port, boolean shouldSucceed) throws Exception {
String jmxUrlStr =
String.format(
"service:jmx:rmi:///jndi/rmi://localhost:%d/jmxrmi",
port);
JMXServiceURL url = new JMXServiceURL(jmxUrlStr);
HashMap<String, ?> env = new HashMap<>();
boolean succeeded;
try {
JMXConnector c = JMXConnectorFactory.connect(url, env);
c.getMBeanServerConnection();
succeeded = true;
} catch(Exception ex) {
succeeded = false;
}
if (succeeded && !shouldSucceed) {
throw new Exception("Could connect to agent, but should not have been possible");
}
if (!succeeded && shouldSucceed) {
throw new Exception("Could not connect to agent");
}
}
public static void getVmInfo() throws Exception {
VirtualMachine vm = VirtualMachine.attach(String.valueOf(10248));
// 获得连接地址
Properties properties = vm.getAgentProperties();
String address = (String) properties.get("com.sun.management.jmxremote.localConnectorAddress");
System.out.println(address);
JMXServiceURL url = new JMXServiceURL(address);
JMXConnector connector = JMXConnectorFactory.connect(url);
RuntimeMXBean rmxb = ManagementFactory.newPlatformMXBeanProxy(connector.getMBeanServerConnection(), "java.lang:type=Runtime", RuntimeMXBean.class);
MemoryMXBean memoryMXBean = ManagementFactory.newPlatformMXBeanProxy(connector.getMBeanServerConnection(), ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.newPlatformMXBeanProxy(connector.getMBeanServerConnection(), ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
System.out.println(operatingSystemMXBean.getSystemCpuLoad());
MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
Map<String, Object> result = new HashMap<>();
//堆提交内存
result.put("heapCommitedMemory", memoryUsage.getCommitted() / KB);
//当前堆内存
result.put("heapUsedMemory", memoryUsage.getUsed() / KB);
//最大堆大小
result.put("heapMaxMemory", memoryUsage.getMax() / KB);
memoryUsage = memoryMXBean.getNonHeapMemoryUsage();
//非堆提交内存
result.put("nonHeapCommitedMemory", memoryUsage.getCommitted() / KB);
//当前非堆内存
result.put("nonHeapUsedMemory", memoryUsage.getUsed() / KB);
//最大非堆大小
result.put("nonHeapMaxMemory", memoryUsage.getMax() / KB);
System.out.println(result);
vm.detach();
}
private void checkServerConnection(MBeanServer hostedServer) throws IOException, MalformedURLException {
// Try to connect using client.
JMXServiceURL serviceURL = new JMXServiceURL(ConnectorServerFactoryBean.DEFAULT_SERVICE_URL);
JMXConnector connector = JMXConnectorFactory.connect(serviceURL);
assertNotNull("Client Connector should not be null", connector);
// Get the MBean server connection.
MBeanServerConnection connection = connector.getMBeanServerConnection();
assertNotNull("MBeanServerConnection should not be null", connection);
// Test for MBean server equality.
assertEquals("Registered MBean count should be the same", hostedServer.getMBeanCount(),
connection.getMBeanCount());
}
public boolean init(){
jmxURL = "service:jmx:rmi:///jndi/rmi://" + ipAndPort + "/jmxrmi";
try {
JMXServiceURL serviceURL = new JMXServiceURL(jmxURL);
JMXConnector connector = JMXConnectorFactory
.connect(serviceURL, null);
conn = connector.getMBeanServerConnection();
if (conn == null) {
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
/**
* Connects to the JMX agent in the local process.
*
* @throws ConnectionFailedException if there was a failure to connect to the local JMX connector in the process
* @throws IOException if the JDK management agent cannot be found and loaded
*/
void connect() throws ConnectionFailedException, IOException {
try {
final JMXServiceURL jmxUrl = getJMXServiceURL();
this.jmxc = JMXConnectorFactory.connect(jmxUrl);
this.server = this.jmxc.getMBeanServerConnection();
} catch (AttachNotSupportedException e) {
throw new ConnectionFailedException("Failed to connect to process '" + this.pid + "'", e);
}
}
/**
* 获取指定程序的jvm 信息
*
* @param pId pId
* @return 没有运行或者获取数据
* @throws Exception 异常
* @see OperatingSystemMXBean
*/
public static OperatingSystemMXBean getOperatingSystemMXBean(String pId) throws Exception {
VirtualMachine virtualMachine = getVirtualMachine(Integer.parseInt(pId));
try {
JMXServiceURL url = getJMXServiceURL(virtualMachine);
if (url == null) {
return null;
}
JMXConnector jmxConnector = JMXConnectorFactory.connect(url, null);
MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
return ManagementFactory.newPlatformMXBeanProxy(mBeanServerConnection, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
} finally {
virtualMachine.detach();
}
}
public MBeanServerConnection call() {
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
try {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(
url, null, mbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
connector = JMXConnectorFactory.connect(addr);
return connector.getMBeanServerConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void testWithException(boolean send)
throws Exception {
ClassLoader zoobyCL = new ZoobyClassLoader();
Class<?> zoobyClass = Class.forName("Zooby", false, zoobyCL);
Object zooby = zoobyClass.newInstance();
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(url, null, pmbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
JMXConnector cc = JMXConnectorFactory.connect(addr);
MBeanServerConnection mbsc = cc.getMBeanServerConnection();
Object rzooby;
if (send) {
System.out.println("Sending object...");
mbsc.setAttribute(getSetName, new Attribute("It", zooby));
rzooby = getSetInstance.getIt();
} else {
System.out.println("Receiving object...");
getSetInstance.setIt(zooby);
rzooby = mbsc.getAttribute(getSetName, "It");
}
if (!rzooby.getClass().getName().equals("Zooby")) {
throw new Exception("FAILED: remote object is not a Zooby");
}
if (rzooby.getClass().getClassLoader() ==
zooby.getClass().getClassLoader()) {
throw new Exception("FAILED: same class loader: " +
zooby.getClass().getClassLoader());
}
cc.close();
cs.stop();
}
@Test
@RunAsClient
public void testRemoteConnection() throws Exception {
String urlString = "service:jmx:remote://localhost:4447";
JMXServiceURL serviceURL = new JMXServiceURL(urlString);
JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL, null);
MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();
int count = connection.getMBeanCount();
assertThat(count).isGreaterThan(1);
jmxConnector.close();
}
@PostConstruct
public void start() {
try {
final JMXServiceURL url = new JMXServiceURL("service:jmx:attach://" + Info.getPid());
final JMXConnector jmxConn = JMXConnectorFactory.connect(url);
client = jmxConn.getMBeanServerConnection();
enabled.set(true);
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug(ExceptionUtils.getStackTrace(e));
}
}
}
public MBeanServerConnection call() {
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
try {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(
url, null, mbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
connector = JMXConnectorFactory.connect(addr);
return connector.getMBeanServerConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public MBeanServerConnection call() {
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
try {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(
url, null, mbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
connector = JMXConnectorFactory.connect(addr);
return connector.getMBeanServerConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public MBeanServerConnection call() {
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
try {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(
url, null, mbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
connector = JMXConnectorFactory.connect(addr);
return connector.getMBeanServerConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws Exception {
JMXServiceURL inputAddr =
new JMXServiceURL("service:jmx:iiop://");
JMXConnectorServer s;
try {
s = JMXConnectorServerFactory.newJMXConnectorServer(inputAddr, null, null);
} catch (java.net.MalformedURLException x) {
try {
Class.forName("javax.management.remote.rmi._RMIConnectionImpl_Tie");
throw new RuntimeException("MalformedURLException thrown but iiop appears to be supported");
} catch (ClassNotFoundException expected) { }
System.out.println("IIOP protocol not supported, test skipped");
return;
}
MBeanServer mbs = MBeanServerFactory.createMBeanServer();
mbs.registerMBean(s, new ObjectName("a:b=c"));
s.start();
JMXServiceURL outputAddr = s.getAddress();
if (!outputAddr.getURLPath().startsWith("/ior/IOR:")) {
throw new RuntimeException("URL path should start with \"/ior/IOR:\": " +
outputAddr);
}
System.out.println("IIOP URL path looks OK: " + outputAddr);
JMXConnector c = JMXConnectorFactory.connect(outputAddr);
System.out.println("Successfully got default domain: " +
c.getMBeanServerConnection().getDefaultDomain());
c.close();
s.stop();
}