【问题标题】:Is MemcacheService fundamentally a singletonMemcacheService 本质上是单例吗
【发布时间】:2014-04-19 14:07:25
【问题描述】:

这个问题的答案似乎很明显,但我需要完全确定。因此,如果答案可以提供权威的参考和明确无歧义的陈述,那就太好了。

假设我有以下两种方法

public CollectionResponse<Dog> getDogs(Identification request){
  MemcacheService syncCacheDog = MemcacheServiceFactory.getMemcacheService();
  syncCacheDog.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
  // ........
  value = (byte[]) syncCacheDog.get(key); // read from cache
    if (value == null) {
      // get value from other source
      // ........

      syncCacheDog.put(key, value); // populate cache
    }
  // ........
}

public CollectionResponse<Cat> getCats(Identification request){
  MemcacheService syncCacheCat = MemcacheServiceFactory.getMemcacheService();
  syncCacheCat.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
  // ........
  value = (byte[]) syncCacheCat.get(key); // read from cache
    if (value == null) {
      // get value from other source
      // ........

      syncCacheCat.put(key, value); // populate cache
    }
  // ........
}

syncCacheDog 和 syncCacheCat 是否指向同一个地图?或者如果我希望他们指向同一张地图,我是否必须创建

static MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();

然后在两个方法中都使用syncCache

另一方面,如果是单例,我该如何维护两个不同的缓存呢? IE。有人可以复制并粘贴我的一个方法并显示它是用命名空间编写的,而不是处理通用字节来处理特定对象(例如 Dog)吗?

【问题讨论】:

    标签: java google-app-engine memcached google-cloud-endpoints


    【解决方案1】:

    是的,根据我使用 GAE 及其文档的经验,Memcache 服务是单例的。更重要的是,不同版本的应用程序都看到相同的缓存。

    为了维护不同的缓存做通常的事情:使用前缀。为不同的类维护一组唯一的前缀应该相对容易——在某个地方有一个枚举,跟踪最大前缀。并且永远不要重复使用旧的前缀号码。

    public enum MemcachePrefix {
      DOGS(1),
      CATS(2);
      // Max: 2.
      public final int value;
      private MemcachePrefix (int value) {this.value = value;}
    };
    
    public class Dog {
      static final MemcachePrefix MEMCACHE_PREFIX = MemcachePrefix.DOGS;
    };
    
    class Main {
      public static void main (String[] args) {
        Dog dog = new Dog();
        System.out.println (dog.MEMCACHE_PREFIX);
      }
    }
    

    还有Namespaces。您可以将其用作命名空间,而不是手动将前缀添加到缓存键中,让 GAE 为您执行键操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多