JMX

   1 package com.example; 
   2  
   3 public interface HelloMBean { 
   4  
   5     public void sayHello(); 
   6     public int add(int x, int y); 
   7     
   8     public String getName(); 
   9      
  10     public int getCacheSize(); 
  11     public void setCacheSize(int size); 
  12 } 

   1 package com.example; 
   2  
   3 public class Hello ... 
   4     implements HelloMBean { 
   5     public void sayHello() { 
   6         System.out.println("hello, world"); 
   7     } 
   8      
   9     public int add(int x, int y) { 
  10         return x + y; 
  11     } 
  12      
  13     public String getName() { 
  14         return this.name; 
  15     }  
  16      
  17     public int getCacheSize() { 
  18         return this.cacheSize; 
  19     } 
  20      
  21     public synchronized void setCacheSize(int size) {
  22         ...
  23     
  24         this.cacheSize = size; 
  25         System.out.println("Cache size now " + this.cacheSize); 
  26     } 
  27     ...
  28      
  29     private final String name = "Reginald"; 
  30     private int cacheSize = DEFAULT_CACHE_SIZE; 
  31     private static final int 
  32         DEFAULT_CACHE_SIZE = 200; 
  33 }

   1 package com.example; 
   2  
   3 import java.lang.management.*; 
   4 import javax.management.*; 
   5  
   6 public class Main { 
   7  
   8     public static void main(String[] args) 
   9         throws Exception { 
  10      
  11         MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); 
  12         ObjectName name = new ObjectName("com.example:type=Hello"); 
  13         Hello mbean = new Hello(); 
  14         mbs.registerMBean(mbean, name); 
  15           
  16         ...
  17      
  18         System.out.println("Waiting forever..."); 
  19         Thread.sleep(Long.MAX_VALUE); 
  20     } 
  21 } 

Without authentication

   1 java -Dfile.encoding=utf8 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port=9001 -Dcom.sun.management.jmxremote.ssl=false -jar example.jar
   2 jconsole hostx:9001

With authentication

   1 java -Dfile.encoding=utf8 -Dcom.sun.management.jmxremote.authenticate=true -Dcom.sun.management.jmxremote.port=9001 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.password.file=/home/userx/jmxremote.password -jar example.jar
   2 jconsole hostx:9001

Java/JMX (last edited 2023-05-29 09:03:22 by 127)