1

I have this code

//net.sf.jsr107cache.Cache, CacheException, CacheFactory, CacheManager all imported
private static Cache getCache() {

    Cache cache = null;
    try {
        CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
        cache = cacheFactory.createCache(Collections.emptyMap());
    } catch (CacheException e) {
        Logger.getLogger(MemcacheUtil.class.getName()).log(Level.SEVERE, 
                "Unable to obtain a cache instance! \n" + e.getMessage());
    }
    return cache;
}

and use it like this

public static byte[] fetchFromMemcache(String key) {
    return (byte[]) getCache().get(key);
}

public static void saveInMemcache(String key, byte[] value) {
    getCache().put(key, value);
}

but annoyingly, nothing gets stored in Memcache and no log message gets printed. Before implementing caching with JCache, I used the Low-level API and had the same problem too. I'm really confused. Is there any special setting (in code, on the appengine console, etc) that needs to be done before Memcache works? Does Memcache just hate me naturally? Is there something I'm doing (or failing to do) in code that's causing all these? Please I'll like to know how to go about this. Thanks!

4

2 回答 2

0

在使用低级 API 使用 Memcache 之前,无需设置特殊设置(在代码中或在 appengine 控制台上)。

我使用这个 API 没有问题。

(如果你愿意,明天我可以给你我用来与内存缓存成功交换数据的代码。

于 2013-02-17T09:08:17.837 回答
0

下面是一个类的示例,该类提供了使用低级 API 从 Memcache 写入/读取的静态方法。优点是我使用缓存的单例实例,提供更好的响应时间。您正在为每个请求创建工厂和缓存服务的新实例,这基本上不是一个好主意。

import java.util.Collection;
import java.util.Map;
import java.util.Set;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.memcache.Stats;


public class AppMemCache {
private static MemcacheService c = MemcacheServiceFactory.getMemcacheService();

public static boolean containsKey(Object key){
    return c.contains(key);
}


public static Object get(Object key){
    return c.get(key);
}

// returns only the cached key/object pairs 
public static Map<String, Object> getAll(Collection<String> keys){
    return c.getAll(keys);
}

public static void put(Object key, Object value){
    c.put(key, value);
}


public static void putAll( Map<String, Object> values){
    c.putAll(values);
}

public static boolean remove(Object key){
    return c.delete(key);
}

@SuppressWarnings({ "rawtypes", "unchecked" })
public static boolean deleteAll(Collection keys){
    Set deletedKeys = c.deleteAll(keys);
    if(deletedKeys.size() == keys.size())
        return true;
    return false;
}

public static Stats getStatistics(){
    return c.getStatistics();
}
}
于 2013-02-18T12:35:00.547 回答