6.4. JCACHE 缓存注解
当 JCache 工件位于 classpath 中时,您可以在 CDI 管理的 Bean 中使用以下 JCache 缓存注解:
@CacheResult- 缓存方法调用的结果。
@CachePut- 缓存方法参数。
@CacheRemoveEntry- 从缓存中删除条目。
@CacheRemoveAll- 从缓存中删除所有条目。
重要
目标类型: 您只能在方法中使用这些 JCache 缓存注解。
要使用 JCache 缓存注解,请在应用程序的 Bean.xml 文件中声明拦截器。
受管环境(应用服务器)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.2" bean-discovery-mode="annotated">
<interceptors>
<class>org.infinispan.jcache.annotation.InjectedCacheResultInterceptor</class>
<class>org.infinispan.jcache.annotation.InjectedCachePutInterceptor</class>
<class>org.infinispan.jcache.annotation.InjectedCacheRemoveEntryInterceptor</class>
<class>org.infinispan.jcache.annotation.InjectedCacheRemoveAllInterceptor</class>
</interceptors>
</beans>
非受管环境(独立)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.2" bean-discovery-mode="annotated">
<interceptors>
<class>org.infinispan.jcache.annotation.CacheResultInterceptor</class>
<class>org.infinispan.jcache.annotation.CachePutInterceptor</class>
<class>org.infinispan.jcache.annotation.CacheRemoveEntryInterceptor</class>
<class>org.infinispan.jcache.annotation.CacheRemoveAllInterceptor</class>
</interceptors>
</beans>
JCACHE 缓存注解示例
以下示例演示了 @CacheResult 注释如何缓存 GreetingService.greet () 方法的结果:
import javax.cache.interceptor.CacheResult;
public class GreetingService {
@CacheResult
public String greet(String user) {
return "Hello" + user;
}
}
使用 JCache 注解时,默认缓存使用注释方法的完全限定名称及其参数类型,例如:org.infinispan.example.GreetingService.greet (java.lang.String)
要使用非默认缓存,请使用 cacheName 属性来指定 cache 名称,如下例所示:
@CacheResult(cacheName = "greeting-cache")