1 Spring cache 配置代理 改为aspectj
1.1 使用配置
1) 添加依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
</dependency>
2) Spring xml配置
<context:load-time-weaver />
<context:component-scan base-package="com.xxx.examples"/>
<cache:annotation-driven cache-manager="cacheManager" mode="aspectj"/>
<!-- spring cache with jdk map -->
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="default"/>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="product"/>
</set>
</property>
</bean>
3) 添加aop.xml
apo.xml 名称固定,位置放在CLASSPATH 下的META-INF/aop.xml
<aspectj>
<weaver options="-verbose -showWeaveInfo">
<include within="com.xxx.examples.cache..*"/>
</weaver>
</aspectj>
4) 编写缓存使用代码
如:
5) 启动方式
因为使用的aspect 加载时候 改变字节码,所以启动方式Vm上要加个VM 参数
-javaagent:C:\Users\xxx\.m2\repository\org\springframework\spring-instrument\4.3.5.RELEASE\spring-instrument-4.3.5.RELEASE.jar
下图是我的main 方法:
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("context-business-cache.xml");
ProductService productService = ctx.getBean(ProductService.class);
productService.queryByIdOut("1");
productService.queryByIdOut("1");
}
下图是我运行的结果:
查询DB
16:47:20.858 [main] DEBUG org.terracotta.offheapstore.paging.UpfrontAllocatingPageSource - Allocating a 1MB buffer from chunk 0 &523239424
16:47:20.859 [main] DEBUG org.terracotta.offheapstore.paging.OffHeapStorageArea - Data area expanded from 1MB to 2MB [occupation=0.0]
只查询了一次db 说明我的配置已经生效
1.2 参考资料
Spring cache配置:
http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/cache.html
Spring aspectj 配置:
http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/aop.html#aop-aj-ltw-spring