15.5. JCache キャッシュアノテーションの使用
API を含む JSR 107(JCACHE)統合に別のモジュールが追加されました。詳細は、本章 を参照してください。
CDI 統合および JCache アーティファクトがクラスパスに存在する場合は、CDI 管理対象 Bean で JCache アノテーションを使用できます。これらのアノテーションは、一般的なユースケースをより簡単に処理できます。この仕様では、以下のキャッシュアノテーションが定義されます。
-
@CacheResult: メソッド呼び出しの結果をキャッシュします。 -
@CachePut- メソッドパラメーターをキャッシュします。 -
@CacheRemoveEntry- キャッシュからエントリーを削除します。 -
@CacheRemoveAll- removes all entries from a cache
これらのアノテーションはメソッドでのみ使用する必要があります。
これらのアノテーションを使用するには、適切なインターセプターを beans.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>
以下のコードのスニペットは @CacheResult アノテーションの使用を示しています。ご覧のとおり、Greetingservice#greet メソッドの結果のキャッシュが簡素化されます。
JCache アノテーションの使用
import javax.cache.interceptor.CacheResult;
public class GreetingService {
@CacheResult
public String greet(String user) {
return "Hello" + user;
}
}
GreetingService と上記のバージョンの最初のバージョンは同じ動作を持ちます。唯一の違いは、使用されるキャッシュのみです。デフォルトでは、パラメーター型(例: org.infinispan.example.GreetingService.greet(java.lang.String))を持つアノテーション付きメソッドの完全修飾名になります。
default 以外のキャッシュを使用することはシンプルです。キャッシュアノテーションの cacheName 属性を使用して名前を指定する必要があります。以下に例を示します。
JCache のキャッシュ名の指定
@CacheResult(cacheName = "greeting-cache")