11.3. リモートキャッシュの注入
リモートキャッシュを注入するために CDI Bean を設定します。
手順
キャッシュ修飾子アノテーションを作成します。
@Remote("mygreetingcache")1 @Qualifier @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface RemoteGreetingCache {2 }キャッシュインジェクションポイントに
@RemoteGreetingCache修飾子を追加します。public class GreetingService { @Inject @RemoteGreetingCache private RemoteCache<String, String> cache; public String greet(String user) { String cachedValue = cache.get(user); if (cachedValue == null) { cachedValue = "Hello " + user; cache.put(user, cachedValue); } return cachedValue; } }
リモートキャッシュをインジェクトするためのヒント
修飾子を使用せずにリモートキャッシュをインジェクトできます。
... @Inject @Remote("greetingCache") private RemoteCache<String, String> cache;複数の Data Grid クラスターがある場合は、クラスターごとに個別のリモート Cache Manager プロデューサーを作成できます。
... import jakarta.transaction.context.ApplicationScoped; public class Config { @RemoteGreetingCache @Produces @ApplicationScoped1 public ConfigurationBuilder builder = new ConfigurationBuilder();2 builder.addServer().host("localhost").port(11222); return new RemoteCacheManager(builder.build()); } }