spring集成Java性能监控调优工具-Javamelody

导读:本篇文章讲解 spring集成Java性能监控调优工具-Javamelody,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

JavaMelody能够在运行环境监测JavaJava EE应用程序服务器。并以图表的形式显示:Java内存和Java CPU使用情况,用户Session数量,JDBC连接数,和http请求、sql请求、jsp页面与业务接口方法(EJB3、spring、Guice)的执行数量,平均执行时间,错误百分比等。图表可以按天,周,月,年或自定义时间段查看。 

https://github.com/javamelody/javamelody

方式一:

新建类:

JavamelodyConfiguration.java

代码如下:

import net.bull.javamelody.MonitoringFilter;
import net.bull.javamelody.SessionListener;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
/**
 * @Author: TEST
 * @Date: 2018/6/10 22:11
 * @Description: JAVAMELODY监控配置
 */
@Configuration
public class JavamelodyConfiguration {
 
    @Bean
    public FilterRegistrationBean monitorFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MonitoringFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }
 
    @Bean
    public ServletListenerRegistrationBean sessionListener(){
        ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean();
        servletListenerRegistrationBean.setListener(new SessionListener());
        return servletListenerRegistrationBean;
    }
 
}

或者:

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
 
import net.bull.javamelody.MonitoringFilter;
import net.bull.javamelody.SessionListener;
 
@Configuration
public class FilterConfig {
	
	/**
	 * 配置javamelody监控
	 * spring boot 会按照order值的大小,从小到大的顺序来依次过滤
	 */
	@Bean
	@Order(Integer.MAX_VALUE-1)
	public FilterRegistrationBean<MonitoringFilter> monitoringFilter() {
		FilterRegistrationBean<MonitoringFilter>  registration = new FilterRegistrationBean<MonitoringFilter>();
		registration.setFilter(new MonitoringFilter());
		registration.addUrlPatterns("/*");
		registration.setName("monitoring");
		return registration;
	}
	
    /**
     *  配置javamelody监听器sessionListener
     */
	@Bean
	public ServletListenerRegistrationBean<SessionListener> servletListenerRegistrationBean() {
		ServletListenerRegistrationBean<SessionListener> slrBean = new ServletListenerRegistrationBean<SessionListener>();
		slrBean.setListener(new SessionListener());
		return slrBean;
	}
}

引入POM.xml

        <!-- javaMelody监控 -->
		<dependency>
			<groupId>net.bull.javamelody</groupId>
			<artifactId>javamelody-core</artifactId>
			<version>1.73.1</version>
		</dependency>
		<dependency>
			<groupId>com.lowagie</groupId>
			<artifactId>itext</artifactId>
			<version>2.1.7</version>
		</dependency>

启动应用,访问:http://localhost/b/monitoring,即可.
 

方式二:

Spring Boot项目中使用JavaMelody进行监控,可以使用spring-boot-starter进行快速整合。

首先,使用maven引入spring-boot-starter:

<dependency>
    <groupId>net.bull.javamelody</groupId>
    <artifactId>javamelody-spring-boot-starter</artifactId>
    <version>1.72.0</version>
</dependency>

这样,在URL http://localhost:8080/monitoring 中就可以访问到JavaMelody监控报告了。

如果想将报告导出为PDF格式,可以在项目中引入iText 2.1.7 dependency:

<!-- itext, option to add PDF export -->
<dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext</artifactId>
    <version>2.1.7</version>
    <exclusions>
        <exclusion>
            <artifactId>bcmail-jdk14</artifactId>
            <groupId>bouncycastle</groupId>
        </exclusion>
        <exclusion>
            <artifactId>bcprov-jdk14</artifactId>
            <groupId>bouncycastle</groupId>
        </exclusion>
        <exclusion>
            <artifactId>bctsp-jdk14</artifactId>
            <groupId>bouncycastle</groupId>
        </exclusion>
    </exclusions>
</dependency>

如果想监控项目中的某些类或方法,可以使用注解 @MonitoredWithSpring ,将此注解添加到类或方法上即可。

更多参考配置可以参见官方GitHub:

https://github.com/javamelody/javamelody/wiki/SpringBootStarter

更多配置:

Configuration

If you want, you can configure other settings by using configuration properties prefixed with javamelody in your application.yml or application.properties.

Example for application.yml:

javamelody:
  # Enable JavaMelody auto-configuration (optional, default: true)
  enabled: true
  # Data source names to exclude from monitoring (optional, comma-separated)
  excluded-datasources: secretSource,topSecretSource
  # Enable monitoring of Spring services and controllers (optional, default: true)
  spring-monitoring-enabled: true
  # Initialization parameters for JavaMelody (optional)
  # See: https://github.com/javamelody/javamelody/wiki/UserGuide#6-optional-parameters
  init-parameters:
    # log http requests:
    log: true
    # to exclude images, css, fonts and js urls from the monitoring:
    #url-exclude-pattern: (/webjars/.*|/css/.*|/images/.*|/fonts/.*|/js/.*)
    # to aggregate digits in http requests:
    #http-transform-pattern: \d+
    # to add basic auth:
    #authorized-users: admin:pwd
    # to change the default storage directory:
    #storage-directory: /tmp/javamelody
    # to change the default "/monitoring" path:
    #monitoring-path: /admin/performance

Example for application.properties:

# Enable JavaMelody auto-configuration (optional, default: true)
javamelody.enabled=true
# Data source names to exclude from monitoring (optional, comma-separated)
javamelody.excluded-datasources=secretSource,topSecretSource
# Enable monitoring of Spring services and controllers (optional, default: true)
javamelody.spring-monitoring-enabled=true
# Initialization parameters for JavaMelody (optional)
# See: https://github.com/javamelody/javamelody/wiki/UserGuide#6-optional-parameters
#    log http requests:
javamelody.init-parameters.log=true
#    to exclude images, css, fonts and js urls from the monitoring:
# javamelody.init-parameters.url-exclude-pattern=(/webjars/.*|/css/.*|/images/.*|/fonts/.*|/js/.*)
#    to aggregate digits in http requests:
# javamelody.init-parameters.http-transform-pattern: \d+
#    to add basic auth:
# javamelody.init-parameters.authorized-users=admin:pwd
#    to change the default storage directory:
# javamelody.init-parameters.storage-directory=/tmp/javamelody
#    to change the default "/monitoring" path:
# javamelody.init-parameters.monitoring-path=/admin/performance

To enable the monitoring of methods annotated with @Scheduled or @Schedules:

  1. add the following in your application.yml:
javamelody:
  advisor-auto-proxy-creator-enabled: false
  scheduled-monitoring-enabled: true
add a dependency on aop in your pom.xml:
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

配置方式:
1.下载地址:http://code.google.com/p/javamelody/downloads/list
目前为止最新版本是1.47.0,下载地址:http://code.google.com/p/javamelody/downloads/detail?name=javamelody-1.47.0.zip&can=2&q=
2.下载后可以解压找到javamelody-1.47.0.jar和jrobin-1.5.9.1.jar,引用到项目中.

3.在web.xml中配置filter:

<filter>  
        <filter-name>monitoring</filter-name>  
        <filter-class>net.bull.javamelody.MonitoringFilter</filter-class>  
        <init-param>  
            <param-name>log</param-name>  
            <param-value>true</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>monitoring</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
    <listener>  
        <listener-class>net.bull.javamelody.SessionListener</listener-class>  
    </listener>  

4.重启项目:打开链接:http://<host>:<port>/projectname/monitoring
例如:http://127.0.0.1:8080/myproj/monitoring

至此,基本配置已完成,可以进行简单的性能监控,下面配置是javamelody与struts2和spring3的集成配置:

 

5.javamelody和struts2集成时配置:


<package name="base" namespace="/" extends="struts-default">  
        <result-types>  
            <result-type name="json" class="org.apache.struts2.json.JSONResult" />  
        </result-types>  
        <interceptors>  
            <!-- javamelody -->  
            <interceptor name="monitoring" class="net.bull.javamelody.StrutsInterceptor" />  
              
            <interceptor-stack name="myStack">  
                <interceptor-ref name="monitoring" />  
                  
                <!-- 
                    struts默认的拦截器 
                -->  
                <interceptor-ref name="defaultStack" />  
            </interceptor-stack>  
        </interceptors>  
        <default-interceptor-ref name="myStack" />  

其他struts配置文件继承base,如下所示:


<package name="example" namespace="/" extends="base">  
        <action name="student_*" class="studentAction" method="{1}">  
            <result name="input">/pub_error.jsp</result>  
        </action>  
    </package>  

6.javamelody与Spring集成:
spring的配置文件中配置:


<bean id= "facadeMonitoringAdvisor" class="net.bull.javamelody.MonitoringSpringAdvisor" >  
         <property name ="pointcut" >  
                 <bean class="org.springframework.aop.support.JdkRegexpMethodPointcut" >  
                         <property name ="pattern" value="com.proj.*.service.*" /><!--正则表达式-->  
                 </bean>  
         </property>  
</bean>  

然后配置:
方式一,web.xml中加入如下配置:

<context-param>
     <param-name> contextConfigLocation</param-name>
             <param-value>
                  classpath:applicationContext*.xml<!--Spring配置文件-->
                  classpath:net/bull/javamelody/monitoring-spring.xml<!--和spring集成时添加-->
             </param-value>
</context-param>

方式二,在spring.xml中加入如下配置:
 

<import resource="classpath:net/bull/javamelody/monitoring-spring.xml" />


7.如果你的所有spring管理的bean都实现了接口,用步骤6中的配置一切OK,但如果有些bean没有实现接口,使用步骤6中的配置将会出错.
则将步骤6中的配置改为(这样将使用cglib代理):
spring配置文件中配置:

<bean id= "facadeMonitoringAdvisor" class="net.bull.javamelody.MonitoringSpringAdvisor" >
         <property name ="pointcut" >
                 <bean class="org.springframework.aop.support.JdkRegexpMethodPointcut" >
                         <property name ="pattern" value="com.proj.*.service.*" /><!--正则表达式-->
                 </bean>
         </property>
</bean>


方式一,web.xml中加入如下配置:
<context-param>
<param-name> contextConfigLocation</param-name>
             <param-value>
                  classpath:applicationContext*.xml<!--Spring配置文件-->
                  classpath:net/bull/javamelody/monitoring-spring-aspectj.xml<!--和spring集成时添加-->
             </param-value>
</context-param>

方式二,在spring.xml中加入如下配置:

<import resource="classpath:net/bull/javamelody/monitoring-spring-aspectj.xml" />

8.在项目中经常这样得到泛型类:

private Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass()  
            .getGenericSuperclass()).getActualTypeArguments()[0];  

使用步骤7配置的cglib代理后会以上代码会出错,可以改为下面这种方式得到泛型类:


private Class<T> entityClass = (Class<T>) getSuperClassGenricType(this  
            .getClass(), 0);  
public static Class<?> getSuperClassGenricType(Class<?> clazz, int index)  
            throws IndexOutOfBoundsException {  
        Type genType = clazz.getGenericSuperclass();  
  
        if (!(genType instanceof ParameterizedType)) {  
            return Object.class;  
        }  
  
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();  
  
        if (index >= params.length || index < 0) {  
            return Object.class;  
        }  
        if (!(params[index] instanceof Class<?>)) {  
            return Object.class;  
        }  
        return (Class<?>) params[index];  
    }  

9.javamelody缓存文件的清除:默认路径一般在tomcat_home/temp/javamelody中.

10.如果需要将结果导出为pdf,只要在项目中引用iText.jar即可自动加上导出pdf的链接.

11.javamelody与Quartz集成需要配置:


<bean id="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
                <property name="exposeSchedulerInRepository" value="true" />  
                ...  
        </bean>  

12.javamelody中配置可选参数:
web.xml中配置,以日志记录为例,如下配置将开启info级别的日志记录:
 


<filter>  
                <filter-name>monitoring</filter-name>  
                <filter-class>net.bull.javamelody.MonitoringFilter</filter-class>  
                <init-param>  
                        <param-name>log</param-name>  
                        <param-value>true</param-value>  
                </init-param>  
        </filter>  

其他可选参数:
system-actions-enabled:默认为true,控制启动或停止system actions garbage collector, http sessions, heap dump, memory histogram, process list, jndi tree, opened jdbc connections, database.

url-exclude-pattern:可配置正则表达式,排除一些url不监控.

http-transform-pattern,sql-transform-pattern,ejb-transform-pattern, spring-transform-pattern, guice-transform-pattern, error-transform-pattern, log-transform-pattern, job-transform-pattern, jsf-transform-pattern, struts-transform-pattern and jsp-transform-pattern :可配置正则表达式,用于合并javamelody统计数据.

storage-directory: 默认为以javamelody,tomcat为例,默认存储路径为TOMCAT_HOME/temp/javamelody

monitoring-path:默认为:/monitoring,可以更改为其他地址,例如改为/mo,则监控地址改为:http://<host>:<port>/projectname/mo

no-database:默认false,配置为true将不监控和数据有关的行为.

disabled:默认false,配置为true将不再监控.

 

更多内容请参考:http://code.google.com/p/javamelody/wiki/UserGuide

 

效果图:

spring集成Java性能监控调优工具-Javamelody
 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/14153.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!