Spring之LoadTimeWeaver——一个需求引发的思考

来源:互联网 发布:aso优化 app排名 编辑:程序博客网 时间:2024/06/05 02:07

转   : 最近有个需求——记录应用中某些接口被调用的轨迹,说白了,记录下入参、出参等即可。

 

我选用ApsectJ解决这个问题,前期讨论说在接口层埋点,但这样有个问题,代码侵入比较严重,需要修改每个需要关注的接口实现类。经过一番讨论,决定使用AOP拦截所有这样的接口。

 

后面又有个新的要求——沙箱环境拦截,生产环境不予拦截。

 

这样就有个眼前的问题需要我们解决,就是同一份应用包如何区分沙箱环境和生产环境并执行不同的行为。同事提醒我可以考虑Spring的LTW,即Load Time Weaving。

 

在Java 语言中,从织入切面的方式上来看,存在三种织入方式:编译期织入、类加载期织入和运行期织入。编译期织入是指在Java编译期,采用特殊的编译器,将切面织入到Java类中;而类加载期织入则指通过特殊的类加载器,在类字节码加载到JVM时,织入切面;运行期织入则是采用CGLib工具或JDK动态代理进行切面的织入。 


AspectJ采用编译期织入和类加载期织入的方式织入切面,是语言级的AOP实现,提供了完备的AOP支持。它用AspectJ语言定义切面,在编译期或类加载期将切面织入到Java类中。 

 

AspectJ提供了两种切面织入方式,第一种通过特殊编译器,在编译期,将AspectJ语言编写的切面类织入到Java类中,可以通过一个Ant或Maven任务来完成这个操作;第二种方式是类加载期织入,也简称为LTW(Load Time Weaving)。 

 

如何使用Load Time Weaving?首先,需要通过JVM的-javaagent参数设置LTW的织入器类包,以代理JVM默认的类加载器;第二,LTW织入器需要一个 aop.xml文件,在该文件中指定切面类和需要进行切面织入的目标类。 

 

下面我将通过一个简单的例子在描述如何使用LTW。

 

例子所作的是记录被调用方法的执行时间和CPU使用率。其实这在实际生产中很有用,与其拉一堆性能测试工具,不如动手做个简单的分析切面,使我们能很快得到一些性能指标。我指的是没有硬性的性能测试需求下。

 

首先我们编写一个被织入的受体类,也就是被拦截的对象。

 

 

Java代码  收藏代码
  1. public class DemoBean {  
  2.     public void run() {  
  3.        System.out.println("Run");  
  4.     }  
  5. }  
   

接着,我们编写分析方法执行效率的切面。

 

Java代码  收藏代码
  1. <span style="font-family: 'Courier New'; color: #646464; font-size: x-small;">@Aspect  
  2. public class ProfilingAspect {  
  3.     @Around("profileMethod()")  
  4.     public Object profile(ProceedingJoinPoint pjp) throws Throwable {  
  5.        StopWatch sw = new StopWatch(getClass().getSimpleName());  
  6.        try {  
  7.            sw.start(pjp.getSignature().getName());  
  8.            return pjp.proceed();  
  9.        } finally {  
  10.            sw.stop();  
  11.            System.out.println(sw.prettyPrint());  
  12.        }  
  13.     }  
  14.     @Pointcut("execution(public * com.shansun..*(..))")  
  15.     public void profileMethod() {}  
  16. }</span>  

 

前文提到,我们还需要一个aop.xml。这个文件要求放在META-INF/aop.xml路径下,以告知AspectJ Weaver我们需要把ProfilingAspect织入到应用的哪些类中。

 

Xml代码  收藏代码
  1. <span style="font-family: 'Courier New'; color: #008080; font-size: x-small;"><!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">  
  2. <aspectj>  
  3.     <weaver>  
  4.        <include within="com.shansun..*" />  
  5.     </weaver>  
  6.     <aspects>  
  7.        <!-- weave in just this aspect -->  
  8.        <aspect name="com.shansun.multidemo.spring.ltw.ProfilingAspect" />  
  9.     </aspects>  
  10. </aspectj></span>  

 

目前为止,本次切面的“攻”和“受”都准备好了,我们还需要一个中间媒介——LoadTimeWeaver。我们将Spring的配置文件添加红色标识内容。

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="GBK"?>  
  2.    
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  8.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  9.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd  
  10.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
  11.     <context:load-time-weaver aspectj-weaving="autodetect" />  
  12.    
  13.     <context:component-scan base-package="com.shansun.multidemo"></context:component-scan>  
  14. </beans>  

 

通过 <context:load-time-weaver  aspectj-weaving="on" /> 使 spring 开启 loadtimeweaver, 注意 aspectj-weaving有三个选项 : on, off, auto-detect, 如果设置为 auto-detect, spring 将会在 classpath 中查找 aspejct 需要的META-INF/aop.xml, 如果找到则开启 aspectj weaving, 这个逻辑在LoadTimeWeaverBeanDefinitionParser#isAspectJWeavingEnabled 方法中:

Java代码  收藏代码
  1. <span style="font-family: 'Courier New'; color: #7f0055; font-size: x-small;"><strong>protected boolean isAspectJWeavingEnabled(String value, ParserContext parserContext) {  
  2.        if ("on".equals(value)) {  
  3.            return true;  
  4.        }  
  5.        else if ("off".equals(value)) {  
  6.            return false;  
  7.        }  
  8.        else {  
  9.            // Determine default...  
  10.            ClassLoader cl = parserContext.getReaderContext().getResourceLoader().getClassLoader();  
  11.            return (cl.getResource(ASPECTJ_AOP_XML_RESOURCE) != null);  
  12.        }  
  13. }</strong></span>  

 

一切都准备就绪——切面类、aop.xml、Spring的配置,我们就创建一个main方法来掩饰LTW的功效吧。

 

Java代码  收藏代码
  1. public class Main {  
  2.     public static void main(String[] args) {  
  3.         ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");  
  4. //      DemoBean bean = (DemoBean) ctx.getBean("demoBean");  
  5.         DemoBean bean = new DemoBean();  
  6.         bean.run();  
  7.     }  
  8. }  

  

 

因为这个LTW使用成熟的AspectJ,我们并不局限于通知Spring beans的方法。所以上述代码中从ApplicationContext中获取Bean和直接实例化一个Bean的效果是一样的。

        

注意,这里以使用Eclipse演示上述代码为例,需要在运行参数中稍作设置,即添加前文提到的-javaagent,来取代默认的类加载器。

 

输出结果如下:

Run

StopWatch 'ProfilingAspect': running time (millis) = 0

-----------------------------------------

ms     %     Task name

-----------------------------------------

      0001 100%  run

 

至此,LTW可以正常使用了,但是麻烦的是我需要在VM参数里加上-javaagent这么个东东,如果不加会如何呢?试试看。

 

Java代码  收藏代码
  1. <span style="font-family: 'Courier New'; color: #ff0000; font-size: x-small;">Exception in thread "main" java.lang.IllegalStateException: Must start with Java agent to use InstrumentationLoadTimeWeaver. See Spring documentation.  
  2.     at org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver.addTransformer(InstrumentationLoadTimeWeaver.java:88)  
  3.     at org.springframework.context.weaving.AspectJWeavingEnabler.postProcessBeanFactory(AspectJWeavingEnabler.java:69)  
  4.     at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:553)  
  5.     at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:536)  
  6.     at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:362)  
  7.     at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)  
  8.     at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)  
  9.     at com.shansun.multidemo.spring.Main.main(Main.java:25)</span>  

必需使用java agent么?仔细观察异常的出处InstrumentationLoadTimeWeaver。再深入这个类的内容,发现异常是由下述方法抛出的。

 

Java代码  收藏代码
  1. public void addTransformer(ClassFileTransformer transformer) {  
  2.        Assert.notNull(transformer, "Transformer must not be null");  
  3.        FilteringClassFileTransformer actualTransformer =  
  4.               new FilteringClassFileTransformer(transformer, this.classLoader);  
  5.        synchronized (this.transformers) {  
  6.            if (this.instrumentation == null) {  
  7.               throw new IllegalStateException(  
  8.                      "Must start with Java agent to use InstrumentationLoadTimeWeaver. See Spring documentation.");  
  9.            }  
  10.            this.instrumentation.addTransformer(actualTransformer);  
  11.            this.transformers.add(actualTransformer);  
  12.        }  
  13. }  

 

不难发现它在校验instrumentation是否为空的时候抛出的异常。有办法啦,重写InstrumentationLoadTimeWeaver的addTransformer方法,隐匿异常即可。

 

 

Java代码  收藏代码
  1. public class ExtInstrumentationLoadTimeWeaver extends  
  2.         InstrumentationLoadTimeWeaver {  
  3.    
  4.     @Override  
  5.     public void addTransformer(ClassFileTransformer transformer) {  
  6.        try {  
  7.            super.addTransformer(transformer);  
  8.        } catch (Exception e) {}  
  9.     }  
  10. }  
 

   

这时,我们还需要做一件事,将Spring配置文件中的load-time-weaver入口设置为我们刚自定义的ExtInstrumentationLoadTimeWeaver即可。

 

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="GBK"?>  
  2.    
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  8.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  9.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd  
  10.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
  11.     <context:load-time-weaver weaver-class="com.shansun.multidemo.spring.ExtInstrumentationLoadTimeWeaver" aspectj-weaving="autodetect" />  
  12.    
  13.     <context:component-scan base-package="com.shansun.multidemo"></context:component-scan>  
  14. </beans>  
 

 

再次运行我们的main方法,发现只输出了如下结果,切面没有起作用。

Run

 

看到了么,同一份代码、同一份配置,只需要在VM启动参数中稍加变化,即可实现同一个应用包在不同环境下可以自由选择使用使用AOP功能。文章开头提到的那个需求也就迎刃而解了。

 

这只是一种解决途径,相信大家会有更好的方案。如果有,请您告诉我。J

 

0 0
原创粉丝点击