6.3. 注入远程缓存


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

流程

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

    @Remote("mygreetingcache") 1
    @Qualifier
    @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface RemoteGreetingCache { 2
    }
    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;
        }
    }

注入远程缓存的提示

  • 您可以注入远程缓存,而无需使用限定符。

       ...
       @Inject
       @Remote("greetingCache")
       private RemoteCache<String, String> cache;
  • 如果您有多个数据中心集群,您可以为集群创建单独的远程缓存管理器制作者。

    ...
    import javax.enterprise.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());
        }
    }
    1
    为应用程序创建 bean 一次。创建缓存管理器的制作者应始终包含 @ApplicationScoped 注释,以避免创建多个缓存管理器,它们是非常重的权重对象。
    2
    创建新的 RemoteCacheManager 实例,它绑定到 @RemoteGreetingCache 限定符。
Red Hat logoGithubRedditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

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

让开源更具包容性

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

關於紅帽

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

© 2024 Red Hat, Inc.