當前位置: 首頁>>代碼示例>>Java>>正文


Java MemcacheService類代碼示例

本文整理匯總了Java中com.google.appengine.api.memcache.MemcacheService的典型用法代碼示例。如果您正苦於以下問題:Java MemcacheService類的具體用法?Java MemcacheService怎麽用?Java MemcacheService使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


MemcacheService類屬於com.google.appengine.api.memcache包,在下文中一共展示了MemcacheService類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getIdentifiable

import com.google.appengine.api.memcache.MemcacheService; //導入依賴的package包/類
@Nullable public IdentifiableValue<V> getIdentifiable(@Nullable K key) {
  TaggedKey<K> taggedKey = tagKey(key);
  MemcacheService.IdentifiableValue rawValue;
  try {
    rawValue = service.getIdentifiable(taggedKey);
  } catch (InvalidValueException e) {
    // Probably a deserialization error (incompatible serialVersionUID or similar).
    log.log(Level.WARNING, "Error getting object from memcache, key: " + key, e);
    return null;
  }
  if (rawValue == null) {
    log.info("cache miss " + taggedKey);
    return null;
  } else {
    log.info("cache hit " + taggedKey + " = " + rawValue);
    return new IdentifiableValue<V>(rawValue);
  }
}
 
開發者ID:ArloJamesBarnes,項目名稱:walkaround,代碼行數:19,代碼來源:MemcacheTable.java

示例2: lookup

import com.google.appengine.api.memcache.MemcacheService; //導入依賴的package包/類
/**
 * Returns null if object id is not known.  (This doesn't mean the id is not
 * assigned; it may be assigned in the object store, which is authoritative,
 * but not in the directory.)
 * @throws IOException
 */
@Nullable public WaveletMapping lookup(SlobId objectId) throws IOException {
  CacheEntry cached = cache.get(objectId);
  if (cached != null) {
    return cached.getCached();
  }
  WaveletMapping result = directory.getWithoutTx(objectId);
  if (result != null) {
    cache.put(objectId, new CacheEntry(result));
    return result;
  } else {
    // We have to use ADD_ONLY_IF_NOT_PRESENT since there may be a concurrent
    // register() also trying to set the value, and that has to take priority.
    cache.put(objectId, new CacheEntry(null), null,
        MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
    return null;
  }
}
 
開發者ID:ArloJamesBarnes,項目名稱:walkaround,代碼行數:24,代碼來源:WaveletDirectory.java

示例3: detect

import com.google.appengine.api.memcache.MemcacheService; //導入依賴的package包/類
public Language detect(String str){
	String key = str;
	String code = "";
	
	// Using the synchronous cache
    MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
    //syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
    code = (String) syncCache.get(key); // read from cache
    if (code == null) {
    	System.out.println("Cache miss");
    	code = detectFromAPI(key);
    	syncCache.put(key, code);
    } else{
    	System.out.println("Cache hit");
    }
		
    String label = getLangaugeLabel(code);
    Language lang = new Language(code, label);
    
	return lang;
	
}
 
開發者ID:tpryan,項目名稱:Atlassian-Connect-Add-On-Starter-Kit-for-App-Engine,代碼行數:23,代碼來源:Translate.java

示例4: doGet

import com.google.appengine.api.memcache.MemcacheService; //導入依賴的package包/類
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
    ServletException {
  String path = req.getRequestURI();
  if (path.startsWith("/favicon.ico")) {
    return; // ignore the request for favicon.ico
  }

  MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
  syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));

  byte[] whoKey = "who".getBytes();
  byte[] countKey = "count".getBytes();

  byte[] who = (byte[]) syncCache.get(whoKey);
  String whoString = who == null ? "nobody" : new String(who);
  resp.getWriter().print("Previously incremented by " + whoString + "\n");
  syncCache.put(whoKey, "Java".getBytes());
  Long count = syncCache.increment(countKey, 1L, 0L);
  resp.getWriter().print("Count incremented by Java = " + count + "\n");
}
 
開發者ID:GoogleCloudPlatform,項目名稱:java-docs-samples,代碼行數:22,代碼來源:MemcacheBestPracticeServlet.java

示例5: countPackages

import com.google.appengine.api.memcache.MemcacheService; //導入依賴的package包/類
/**
 * @return the number of packages
 */
public static int countPackages() {
    final String key =
            NWUtils.class.getName() + "[email protected]" +
            NWUtils.getDataVersion();
    MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
    syncCache.setErrorHandler(ErrorHandlers
            .getConsistentLogAndContinue(Level.INFO));
    Integer value = (Integer) syncCache.get(key); // read from cache
    if (value == null) {
        ShardedCounter sc =
                ShardedCounter.getOrCreateCounter("NumberOfPackages", 2);
        value = sc.getCount();
        if (sc.getCount() == 0) {
            Objectify ofy = DefaultServlet.getObjectify();
            sc.increment(ofy.query(Package.class).count());
            value = sc.getCount();
        }
        syncCache.put(key, value); // populate cache
    }
    return value;
}
 
開發者ID:tim-lebedkov,項目名稱:npackd-gae-web,代碼行數:25,代碼來源:NWUtils.java

示例6: put

import com.google.appengine.api.memcache.MemcacheService; //導入依賴的package包/類
public boolean put(Object key, long txTimestamp, Object value) {

        String versionKey = versionKey(key);


        // check for the current version cached
        MemcacheService.IdentifiableValue currentVersion = memcacheService.getIdentifiable(versionKey);
        
        if (!isNewer(currentVersion, txTimestamp)) {
            return false;
        }

        // store the value first so we don't risk the version number appearing before the
        // corresponding value is written
        memcacheService.put(valueKey(key, txTimestamp), value);

        // Now update the version key if a newer version hasn't already been stored
        while (!updateVersionKey(versionKey, currentVersion, txTimestamp)) {
            // ... in the meantime another process has updated the cache with a version
            // but we don't know if it's older or younger, so we have to try again
            currentVersion = memcacheService.getIdentifiable(versionKey);
        }
        return true;
    }
 
開發者ID:bedatadriven,項目名稱:appengine-hibernate,代碼行數:25,代碼來源:AbstractMemcacheRegion.java

示例7: doGet

import com.google.appengine.api.memcache.MemcacheService; //導入依賴的package包/類
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
	
  	// Query for conferences with less than 5 seats lef
	Iterable<Conference> iterable = ofy().load().type(Conference.class)
	                .filter("seatsAvailable <", 5)
	                .filter("seatsAvailable >", 0);
    List<String> conferenceNames = new ArrayList<>(0);
    for (Conference conference : iterable) {
        conferenceNames.add(conference.getName());
    }
    if (conferenceNames.size() > 0) {
        StringBuilder announcementStringBuilder = new StringBuilder(
                "Last chance to attend! The following conferences are nearly sold out: ");
        Joiner joiner = Joiner.on(", ").skipNulls();
        announcementStringBuilder.append(joiner.join(conferenceNames));
        MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService();
        memcacheService.put(Constants.MEMCACHE_ANNOUNCEMENTS_KEY,
                announcementStringBuilder.toString());
    }
    response.setStatus(204);
}
 
開發者ID:udacity,項目名稱:ud859,代碼行數:24,代碼來源:SetAnnouncementServlet.java

示例8: doGet

import com.google.appengine.api.memcache.MemcacheService; //導入依賴的package包/類
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    final String uuid = request.getParameter(UpdatePositionServletImpl.PARAMETER_UUID);
    if (uuid == null || uuid.trim().equals("")) {
        response.sendError(HttpStatus.SC_BAD_REQUEST, "?uuid= mandatory");
    }
    
    final MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
    syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
    final Object inMemory = syncCache.get(uuid);
    
    if (inMemory == null) {
        response.sendError(HttpStatus.SC_NOT_FOUND, "element not found");
    }
    
    final Cache cache = Cache.from(inMemory);
    response.getWriter().write(cache.toString());
}
 
開發者ID:sylvek,項目名稱:sharemyposition,代碼行數:20,代碼來源:RetrievePositionServletImpl.java

示例9: IndexServlet

import com.google.appengine.api.memcache.MemcacheService; //導入依賴的package包/類
/**
 * Constructor.
 *
 * @param channelService service for handling channel communication
 * @param networks used to get a list of networks
 * @param userService the App Engine service for user management
 * @param memcacheService the App Engine caching service
 * @param expirationDelta the cache expiration delta in seconds
 * @param authorizationCodeFlowFactory used to get an OAuth2 flow
 * @param redirectUrl where to direct the user once authorization is done
 */
@Inject
public IndexServlet(ChannelService channelService,
    Networks networks,
    UserService userService,
    MemcacheService memcacheService,
    @Named("expirationDelta") int expirationDelta,
    AuthorizationCodeFlowFactory authorizationCodeFlowFactory,
    @Named("redirectUrl") String redirectUrl) {
  super(authorizationCodeFlowFactory, redirectUrl);
  this.channelService = channelService;
  this.networks = networks;
  this.memcacheService = memcacheService;
  this.userService = userService;
  this.expirationDelta = expirationDelta;
}
 
開發者ID:googleads,項目名稱:googleads-dfp-java-dfp-playground,代碼行數:27,代碼來源:IndexServlet.java

示例10: doGet

import com.google.appengine.api.memcache.MemcacheService; //導入依賴的package包/類
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  try {
    URLFetchServiceFactory.getURLFetchService()
        .fetchAsync(new URL("http://www.example.com/asyncWithGet"))
        .get();
  } catch (Exception anythingMightGoWrongHere) {
    // fall through
  }
  URLFetchServiceFactory.getURLFetchService()
      .fetchAsync(new URL("http://www.example.com/asyncWithoutGet"));
  MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
  String randomKey = "" + Math.random();
  String randomValue = "" + Math.random();
  memcache.put(randomKey, randomValue);
  resp.setContentType("text/plain");
  resp.getOutputStream().println(randomKey);
}
 
開發者ID:GoogleCloudPlatform,項目名稱:appengine-java-vm-runtime,代碼行數:19,代碼來源:AppstatsMonitoredServlet.java

示例11: aquire

import com.google.appengine.api.memcache.MemcacheService; //導入依賴的package包/類
public boolean aquire() {
    MemcacheService memcache = MemcacheServiceFactory.getMemcacheService(ns);
    long start = System.currentTimeMillis();
    while (true) {
        if (memcache.increment(key, 1L, 0L) == 1L) {
            return true;
        }
        if (System.currentTimeMillis() - start > maxWait) {
            return false;
        }
        try {
            Thread.sleep(100L);
        } catch (InterruptedException e) {
        }
    }
}
 
開發者ID:feroult,項目名稱:yawp,代碼行數:17,代碼來源:Mutex.java

示例12: get

import com.google.appengine.api.memcache.MemcacheService; //導入依賴的package包/類
public Object get(final String key) {
    final Object[] count = new Object[1];
    count[0] = null;

    final RetryingExecutor executor = new RetryingExecutor(3, 500, new IClosure() {
        public void execute(final Object arg0) throws Exception {
            final MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
            count[0] = memcache.get(key);
        }
    }, null);

    try {
        executor.startExecution();
    } catch (final Throwable e) {
        log.log(Level.WARNING, "Problems when getting object from MemCache. Key [" + key + "]: " + e.getMessage(), e);
    }
    return count[0];
}
 
開發者ID:ZupCat,項目名稱:simple-datastore,代碼行數:19,代碼來源:MemcacheManager.java

示例13: findByBuildTypeIdOrderByBuildIdDesc

import com.google.appengine.api.memcache.MemcacheService; //導入依賴的package包/類
/**
 * Finds the {@code TestReport} with the given build type id ordered by build id in the descendant order.
 *
 * @param buildTypeId      the build type id.
 * @param limit            the optional fetch limit, by default {@link com.google.appengine.tck.site.endpoints.TestReport#DEFAULT_FETCH_LIMIT}.
 * @param reports          the reports entry point
 * @return the matching test reports list or an empty one if none.
 */
@SuppressWarnings("unchecked")
public static List<TestReport> findByBuildTypeIdOrderByBuildIdDesc(String buildTypeId, Optional<Integer> limit, Reports reports) {
    final MemcacheService memcacheService = reports.getMemcacheService();
    List<TestReport> results = (List<TestReport>) memcacheService.get(buildTypeId);
    if (results == null) {
        final Filter buildTypeFilter = new Query.FilterPredicate("buildTypeId", FilterOperator.EQUAL, buildTypeId);
        final Query query = new Query(TEST_REPORT).setFilter(buildTypeFilter).addSort("buildId", DESCENDING);

        final DatastoreService datastoreService = reports.getDatastoreService();
        final PreparedQuery preparedQuery = datastoreService.prepare(query);
        final List<Entity> entities = preparedQuery.asList(FetchOptions.Builder.withLimit(limit.or(DEFAULT_FETCH_LIMIT)));

        results = new ArrayList<>();
        for (Entity oneEntity : entities) {
            final TestReport report = from(oneEntity);
            results.add(report);
        }

        memcacheService.put(buildTypeId, results);
    }
    return results;
}
 
開發者ID:GoogleCloudPlatform,項目名稱:appengine-tck,代碼行數:31,代碼來源:TestReport.java

示例14: testPutAllAddOnlyIfNotPresent

import com.google.appengine.api.memcache.MemcacheService; //導入依賴的package包/類
@Test
public void testPutAllAddOnlyIfNotPresent() {
    HashMap<Object, Object> firstValues = new HashMap<Object, Object>();
    firstValues.put("key1", "firstValue1");
    firstValues.put("key2", "firstValue2");

    HashMap<Object, Object> secondValues = new HashMap<Object, Object>();
    secondValues.put("key1", "secondValue1");
    secondValues.put("key2", "secondValue2");

    unwrap(service.putAll(firstValues));
    unwrap(service.putAll(secondValues, null, MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT));

    for (Map.Entry<Object, Object> entry : firstValues.entrySet()) {
        assertEquals(entry.getValue(), unwrap(service.get(entry.getKey())));
    }
}
 
開發者ID:GoogleCloudPlatform,項目名稱:appengine-tck,代碼行數:18,代碼來源:MemcacheAsyncTest.java

示例15: testPutAllAddOnlyIfNotPresent

import com.google.appengine.api.memcache.MemcacheService; //導入依賴的package包/類
@Test
public void testPutAllAddOnlyIfNotPresent() {
    HashMap<Object, Object> firstValues = new HashMap<Object, Object>();
    firstValues.put("key1", "firstValue1");
    firstValues.put("key2", "firstValue2");

    HashMap<Object, Object> secondValues = new HashMap<Object, Object>();
    secondValues.put("key1", "secondValue1");
    secondValues.put("key2", "secondValue2");

    memcache.putAll(firstValues);
    memcache.putAll(secondValues, null, MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);

    for (Map.Entry<Object, Object> entry : firstValues.entrySet()) {
        assertEquals(entry.getValue(), memcache.get(entry.getKey()));
    }
}
 
開發者ID:GoogleCloudPlatform,項目名稱:appengine-tck,代碼行數:18,代碼來源:MemcacheTest.java


注:本文中的com.google.appengine.api.memcache.MemcacheService類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。