`
zhangwei_david
  • 浏览: 469864 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

JMX之将Spring Bean 输出为JMX并为远程服务暴露Mbean

    博客分类:
  • JMX
 
阅读更多

    JMX 是Java 管理扩展(Java Management Extensions);JMX是一种管理和监控系统资源的技术。这种规范为运行管理系统体统了强大的功能。这些资源有托管Bean(managed beans,MBeans)表示。Spring 可以将任何Spring 管理的Bean输出为Mbean,而不需要在该Bean中定义任何JMX特有的属性。可以简单地通过声明一个MbeanExporter实例来完成将普通Bean 导出为Mbean.

  •        如果Bean实现了任意一个JMX的管理接口 MBeanExporter可以简单地通过自动检测过程注册服务器的MBean
  •        如果Bean没有实现JMX的挂历接口 MBeanExporter通过使用MBeanInfoAssembler创建管理信息

   

 

 

/**
 *定义一个普通的接口
 *
 * @author zhangwei_david
 * @version $Id: HiMBean.java, v 0.1 2015年1月24日 下午1:16:15 zhangwei_david Exp $
 */
public interface HiMBean {
    /**
     *打招呼
     */
    public void sayHello();

    /**
     * 加法计算器
     *
     * @param x
     * @param y
     * @return
     */
    public int add(int x, int y);

    /**
     * 获取名称
     *
     * @return
     */
    public String getName();

    /**
     *获取缓存大小
     *
     * @return
     */
    public int getCacheSize();

    /**
     *设置缓存大小
     *
     * @param size
     */
    public void setCacheSize(int size);
}

 

/**
 *简单实现类
 * @author Lenovo
 * @version $Id: Hi.java, v 0.1 2014年9月26日 下午2:48:09 Lenovo Exp $
 */
public class HiMbeanImpl implements HiMBean {

    private final String     name               = "Reginald";
    private int              cacheSize          = DEFAULT_CACHE_SIZE;
    private static final int DEFAULT_CACHE_SIZE = 200;

    /**
     * @see com.cathy.demo.jmx.notifications.HiMBean#sayHello()
     */
    public void sayHello() {
        System.out.println("Hello," + getName());
    }

    /**
     * @see com.cathy.demo.jmx.notifications.HiMBean#add(int, int)
     */
    public int add(int x, int y) {
        return x + y;
    }

    /**
     * @see com.cathy.demo.jmx.notifications.HiMBean#getName()
     */
    public String getName() {
        return name;
    }

    /**
     * @see com.cathy.demo.jmx.notifications.HiMBean#getCacheSize()
     */
    public int getCacheSize() {
        return cacheSize;
    }

    /**
     * @see com.cathy.demo.jmx.notifications.HiMBean#setCacheSize(int)
     */
    public void setCacheSize(int size) {
        cacheSize = size;
    }

}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:task="http://www.springframework.org/schema/task" xmlns:util="http://www.springframework.org/schema/util"
	xmlns:jaxws="http://cxf.apache.org/jaxws"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://www.springframework.org/schema/jee 
		http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
		http://www.springframework.org/schema/task  
        http://www.springframework.org/schema/task/spring-task-3.1.xsd  
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.0.xsd
        http://cxf.apache.org/jaxws
        http://cxf.apache.org/schemas/jaxws.xsd
		">
	<aop:aspectj-autoproxy />

	<context:annotation-config />
	<context:component-scan base-package="com.cathy.demo.jmx.*" />
	<!-- HiMbean -->
	<bean id="hiMbean" class="com.cathy.demo.jmx.HiMbeanImpl"/>
	
	<bean id="mbeanExporter" class="org.springframework.jmx.export.MBeanExporter">
		<property name="beans">
			<util:map>
				<entry key="bean:name=hiMbean" value-ref="hiMbean"/>
			</util:map>
		</property>
	
	</bean>
	
</beans>

 

/**
 *
 * @author zhangwei
 * @version $Id: AsyncDemoTest.java, v 0.1 2014年9月26日 下午10:43:43 zhangwei Exp $
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:META-INF/spring/jmx-beans.xml")
public class JmxTest {

    @Test
    public void testAsync() throws InterruptedException {
        TimeUnit.HOURS.sleep(1);
    }

}

 

jconsole的结果:



 

如果不是用Spring导出一个Mban的化 代码如下:

/**
 *
 * @author Lenovo
 * @version $Id: Main.java, v 0.1 2014年9月26日 下午4:08:31 Lenovo Exp $
 */
public class Main {

    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        //获取Mean的平台服务
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        // 对即将被注册的MBean 构造一个ObjectName
        ObjectName objectName = new ObjectName("com.cathy.demo.jmx:type=Hi");
        // 创建一个Mbean
        RequiredModelMBean mbean = new RequiredModelMBean();
        HiMbeanImpl hiMbean = new HiMbeanImpl();
        mbean.setManagedResource(hiMbean, "objectReference");

        ModelMBeanAttributeInfo name = new ModelMBeanAttributeInfo("name", "java.lang.String",
            "userName", true, true, false, new DescriptorSupport(new String[] { "name=name",
                    "descriptorType=attribute", "getMethod=getName", "setMethod=setName" }));
        ModelMBeanOperationInfo sayHello = new ModelMBeanOperationInfo("say Hello", hiMbean
            .getClass().getMethod("sayHello"));
        ModelMBeanOperationInfo getName = new ModelMBeanOperationInfo("get userName", hiMbean
            .getClass().getMethod("getName"));
        ModelMBeanInfo mbeanInfo = new ModelMBeanInfoSupport("HiMbean", "Test",
            new ModelMBeanAttributeInfo[] { name }, null, new ModelMBeanOperationInfo[] { sayHello,
                    getName }, null);
        mbean.setModelMBeanInfo(mbeanInfo);
        // 将Mbean 注册到MBeanServer
        mbs.registerMBean(mbean, objectName);
        // 一直等待
        System.out.println("Waiting forever...");
        Thread.sleep(Long.MAX_VALUE);

    }
}

 

 

为远程服务暴露一个Mbean

      有时候需要将本地的Mbean暴露出去,供远程调用;在Spring可以使用ConnectorServerFactoryBean创建一个JMX连接服务器。

 

<bean id="rmiRegistry" class="org.springframework.remoting.rmi.RmiRegistryFactoryBean"/>
	<bean id="connectorServer" class="org.springframework.jmx.support.ConnectorServerFactoryBean" depends-on="rmiRegistry">
		<property name="serviceUrl" value="service:jmx:rmi://localhost/jndi/rmi://localhost:1099/hiMbean"/>
	</bean>

 

通过Jconsole 访问远程Mbean



 

已经为远程服务暴露了Mbean 那么如果在Spring 中远程调用Mbean又是什么样的呢?

	<bean id="mbeanServerConnection" class="org.springframework.jmx.support.MBeanServerConnectionFactoryBean">
		<property name="serviceUrl" value="service:jmx:rmi://localhost/jndi/rmi://localhost:1099/hiMbean"/>
	</bean>
	<bean id="hiMbeanProxy" class="org.springframework.jmx.access.MBeanProxyFactoryBean">
		<property name="server" ref="mbeanServerConnection"/>
		<property name="objectName" value="bean:name=hiMbean"/>
		<property name="proxyInterface" value="com.cathy.demo.jmx.HiMBean"/>
	</bean>

 

/**
 *
 * @author zhangwei
 * @version $Id: AsyncDemoTest.java, v 0.1 2014年9月26日 下午10:43:43 zhangwei Exp $
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:META-INF/spring/jmx-beans.xml")
public class JmxTest {
    @Autowired
    private HiMBean hiMbeanProxy;

    @Test
    public void testAsync() throws InterruptedException {

        hiMbeanProxy.sayHello();
        TimeUnit.HOURS.sleep(1);
    }

}

 结果是:

一月 24, 2015 2:16:34 下午 org.springframework.test.context.TestContextManager retrieveTestExecutionListeners
信息: @TestExecutionListeners is not present for class [class com.cathy.demo.schedule.JmxTest]: using defaults.
一月 24, 2015 2:16:34 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from URL [file:/H:/Alipay.com/workspace4alipay/demo/target/classes/META-INF/spring/jmx-beans.xml]
一月 24, 2015 2:16:35 下午 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider registerDefaultFilters
信息: JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
一月 24, 2015 2:16:35 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.GenericApplicationContext@7c703b: startup date [Sat Jan 24 14:16:35 CST 2015]; root of context hierarchy
一月 24, 2015 2:16:35 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@afc191: defining beans [org.springframework.aop.config.internalAutoProxyCreator,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,hiMbean,mbeanExporter,rmiRegistry,connectorServer,mbeanServerConnection,hiMbeanProxy,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
一月 24, 2015 2:16:35 下午 org.springframework.jmx.export.MBeanExporter afterPropertiesSet
信息: Registering beans for JMX exposure on startup
一月 24, 2015 2:16:35 下午 org.springframework.jmx.export.MBeanExporter registerBeanInstance
信息: Located managed bean 'bean:name=hiMbean': registering with JMX server as MBean [bean:name=hiMbean]
一月 24, 2015 2:16:35 下午 org.springframework.remoting.rmi.RmiRegistryFactoryBean getRegistry
信息: Looking for RMI registry at port '1099'
一月 24, 2015 2:16:36 下午 org.springframework.remoting.rmi.RmiRegistryFactoryBean getRegistry
信息: Could not detect RMI registry - creating new one
一月 24, 2015 2:16:36 下午 org.springframework.jmx.support.ConnectorServerFactoryBean afterPropertiesSet
信息: JMX connector server started: javax.management.remote.rmi.RMIConnectorServer@9d0b9d
Hello,Reginald

 

  • 大小: 32 KB
  • 大小: 33.8 KB
0
0
分享到:
评论

相关推荐

    lanlan2017#JavaReadingNotes#18.0 第18章 使用JMX监控Spring1

    第18章 使用JMX监控Spring本章内容:使用Actuator端点的MBean将Spring bean暴露为MBean发布通知JMX(Java Manage

    Spring in Action(第2版)中文版

    12.4.1将springbean输出为mbean 12.4.2远程访问mbean 12.4.3处理通知 12.5小结 第三部分spring客户端 第13章处理web请求 13.1开始springmvc之旅 13.1.1请求生命中的一天 13.1.2配置dispatcherservlet ...

    Spring in Action(第二版 中文高清版).part2

    12.4.1 将Spring Bean输出为MBean 12.4.2 远程访问MBean 12.4.3 处理通知 12.5 小结 第三部分 Spring客户端 第13章 处理Web请求 13.1 开始Spring MVC之旅 13.1.1 请求生命中的一天 13.1.2 配置...

    Spring in Action(第二版 中文高清版).part1

    12.4.1 将Spring Bean输出为MBean 12.4.2 远程访问MBean 12.4.3 处理通知 12.5 小结 第三部分 Spring客户端 第13章 处理Web请求 13.1 开始Spring MVC之旅 13.1.1 请求生命中的一天 13.1.2 配置...

    Spring 2.0 开发参考手册

    20.2. 输出bean到JMX 20.2.1. 创建一个MBeanServer 20.2.2. 复用现有的MBeanServer 20.2.3. MBean的惰性初始化 20.2.4. MBean的自动注册 20.2.5. 控制注册行为 20.3. 控制bean的管理接口 20.3.1. ...

    Spring-Reference_zh_CN(Spring中文参考手册)

    1. 简介 1.1. 概览 1.2. 使用场景 2. Spring 2.0 的新特性 2.1. 简介 2.2. 控制反转(IoC)容器 2.2.1. 更简单的XML配置 2.2.2. 新的bean作用域 2.2.3. 可扩展的XML编写 ... 将 Spring Beans 注入到 Tapestry ...

    Spring中文帮助文档

    2.6.4. 将Spring 应用程序上下文部署为JCA adapter 2.6.5. 计划任务 2.6.6. 对Java 5 (Tiger) 支持 2.7. 移植到Spring 2.5 2.7.1. 改变 2.8. 更新的样例应用 2.9. 改进的文档 I. 核心技术 3. IoC(控制反转)...

    Spring API

    2.6.4. 将Spring 应用程序上下文部署为JCA adapter 2.6.5. 计划任务 2.6.6. 对Java 5 (Tiger) 支持 2.7. 移植到Spring 2.5 2.7.1. 改变 2.8. 更新的样例应用 2.9. 改进的文档 I. 核心技术 3. IoC(控制反转)...

    Spring攻略(第二版 中文高清版).part1

    10.4 通过BlazeDS/Spring暴露服务 411 10.4.1 问题 411 10.4.2 解决方案 411 10.4.3 工作原理 411 10.5 使用服务器端对象 418 10.5.1 问题 418 10.5.2 解决方案 418 10.5.3 工作原理 418 10.6 使用...

    spring chm文档

    17.2.1. 使用 RmiServiceExporter 暴露服务 17.2.2. 在客户端链接服务 17.3. 使用Hessian或者Burlap通过HTTP远程调用服务 17.3.1. 为Hessian配置DispatcherServlet 17.3.2. 使用HessianServiceExporter暴露你的...

    Spring攻略(第二版 中文高清版).part2

    10.4 通过BlazeDS/Spring暴露服务 411 10.4.1 问题 411 10.4.2 解决方案 411 10.4.3 工作原理 411 10.5 使用服务器端对象 418 10.5.1 问题 418 10.5.2 解决方案 418 10.5.3 工作原理 418 10.6 使用...

    spring-boot-reference.pdf

    52.1. Customizing MBean Names 52.2. Disabling JMX Endpoints 52.3. Using Jolokia for JMX over HTTP 52.3.1. Customizing Jolokia 52.3.2. Disabling Jolokia 53. Loggers 53.1. Configure a Logger 54. Metrics...

    springboot参考指南

    将Spring Data仓库暴露为REST端点 vii. 68. 数据库初始化 i. 68.1. 使用JPA初始化数据库 ii. 68.2. 使用Hibernate初始化数据库 iii. 68.3. 使用Spring JDBC初始化数据库 iv. 68.4. 初始化Spring Batch数据库 v. ...

Global site tag (gtag.js) - Google Analytics