您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页spring cache 配置使用aspectj LTW

spring cache 配置使用aspectj LTW

来源:二三娱乐

spring cache 提供了基于注解的缓存配置方法,其实现原理和事务管理的实现是一样的, 都是通过 spring aop来实现的。spring aop 有一个问题, 默认 aop的实现是使用java 动态代理技术来实现的, 这样就会导致,同一个对象内的方法之间的调用,是不会被aop拦截到的。

要解决这个问题,我们可以选择调整代码的位置外,让缓存的方法和调用它的方法分离在不同的类中,但是这种解决方案是不完美的,会导致原本内聚的类,分散在了不同的地方。

除了调整代码外,还有什么办法能支持这种情况?
使用AspectJ 进行 织入。

AspectJ 织入器weaver 支持三种织入方式:

  • compile-time weaving 使用aspectj 编译器进行编译源码
  • post-compile weaving 对class 文件进行织入
  • load-time weaving(LTW) 当class loader 加载类的时候,进行织入

使用

通过JVM的-javaagent 加载代理,在代理内持有Instrumentation 对象,方便后续的注册class translate hook。

-javaagent:D:\lib\spring-instrument\spring-instrument-4.3.0.RELEASE.jar

spring cache 配置 mode="aspectj"


<?xml version="1.0" encoding="UTF-8"?>
<beans  
       
       
       xsi:schemaLocation="    
        
        

    <context:load-time-weaver/>

    <cache:annotation-driven mode="aspectj"/>

    <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
        <constructor-arg ref="redisTemplate"/>
    </bean>

    <bean id="propertyConfigurer3" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="order" value="3" />
        <property name="ignoreUnresolvablePlaceholders" value="true" />
        <property name="locations">
            <list>
                <value>classpath:redis.properties</value>
            </list>
        </property>
    </bean>

    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="minIdle" value="${redis.minIdle}" />
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxTotal" value="${redis.maxActive}" />
        <property name="maxWaitMillis" value="${redis.maxWait}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>

    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.host}" />
        <property name="port" value="${redis.port}" />
        <property name="password" value="${redis.password}" />
        <property name="usePool" value="true" />
        <property name="poolConfig" ref="poolConfig" />
    </bean>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory"   ref="connectionFactory" />
    </bean>


    <bean id="redisContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory"/>
    </bean>

</beans>


META-INF/aop.xml 声明需要进行织入的目标类



<aspectj>
    <weaver options="-verbose -showWeaveInfo">
        <include within="com.xxx..*"/>
    </weaver>
</aspectj>


Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务