MemcacheService基本上是一个单例

时间:2014-04-19 14:07:26

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

这个问题的答案显而易见,但我需要完全确定。因此,如果答案可以提供明确的非模糊语句的权威参考,那就太棒了。

说我有以下两种方法

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

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

1 个答案:

答案 0 :(得分: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为您执行关键操作。