11.3. 注入远程缓存


设置 CDI Bean 以注入远程缓存。

流程

  1. 创建缓存限定符注解。

    @Remote("mygreetingcache") 
    1
    
    @Qualifier
    @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface RemoteGreetingCache { 
    2
    
    }
    Copy to Clipboard Toggle word wrap
    1
    要注入的缓存的名称。
    2
    创建 @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;
        }
    }
    Copy to Clipboard Toggle word wrap

注入远程缓存的提示

  • 您可以在不使用限定符的情况下注入远程缓存。

       ...
       @Inject
       @Remote("greetingCache")
       private RemoteCache<String, String> cache;
    Copy to Clipboard Toggle word wrap
  • 如果您有多个 Data Grid 集群,您可以为每个集群创建单独的远程缓存管理器制作者。

    ...
    import jakarta.transaction.context.ApplicationScoped;
    
    public class Config {
    
        @RemoteGreetingCache
        @Produces
        @ApplicationScoped 
    1
    
        public ConfigurationBuilder builder = new ConfigurationBuilder(); 
    2
    
            builder.addServer().host("localhost").port(11222);
            return new RemoteCacheManager(builder.build());
        }
    }
    Copy to Clipboard Toggle word wrap
    1
    为应用创建 bean 一次。创建缓存管理器的制作者应始终包含 @ApplicationScoped 注释,以避免创建多个缓存管理器,它们是重度的 weight 对象。
    2
    创建新的 RemoteCacheManager 实例,该实例绑定到 @RemoteGreetingCache qualifier。
返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2025 Red Hat