Package com.google.appengine.api.memcache

Examples of com.google.appengine.api.memcache.MemcacheService


  @Autowired
  private GuestDao guestDao;

  public List<Guest> getGuests() {
    MemcacheService ms = MemcacheServiceFactory.getMemcacheService();

    if (!ms.contains(GUESTS_MEMCACHE_KEY)) {
      ms.put(GUESTS_MEMCACHE_KEY, guestDao.getGuests());
    }

    return (List<Guest>) ms.get(GUESTS_MEMCACHE_KEY);
  }
View Full Code Here


    return (List<Guest>) ms.get(GUESTS_MEMCACHE_KEY);
  }

  public List<Guest> getGuests(Date createdAfter) {
    MemcacheService ms = MemcacheServiceFactory.getMemcacheService();

    if (!ms.contains(GUESTS_MEMCACHE_KEY)) {
      ms.put(GUESTS_MEMCACHE_KEY, guestDao.getGuests(createdAfter));
    }

    return (List<Guest>) ms.get(GUESTS_MEMCACHE_KEY);
  }
View Full Code Here

    return (List<Guest>) ms.get(GUESTS_MEMCACHE_KEY);
  }

  public void storeGuest(Guest guest) {
    MemcacheService ms = MemcacheServiceFactory.getMemcacheService();

    guestDao.storeGuest(guest);

    ms.delete(GUESTS_MEMCACHE_KEY);
  }
View Full Code Here

            cleanSession(request);
            return;
        }

        boolean locked = false;
        MemcacheService memcache = null;
        String mutex = MUTEX_BASE + session.getId();
        memcache = MemcacheServiceFactory.getMemcacheService();
        try {
            // try to get lock
            long started = new Date().getTime();
            // non-UIDL requests will try indefinitely
            while (requestType != RequestType.UIDL
                    || new Date().getTime() - started < MAX_UIDL_WAIT_MILLISECONDS) {
                locked = memcache.put(mutex, 1, Expiration.byDeltaSeconds(40),
                        MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
                if (locked) {
                    break;
                }
                try {
                    Thread.sleep(RETRY_AFTER_MILLISECONDS);
                } catch (InterruptedException e) {
                    getLogger().finer(
                            "Thread.sleep() interrupted while waiting for lock. Trying again. "
                                    + e);
                }
            }

            if (!locked) {
                // Not locked; only UIDL can get trough here unlocked: tell
                // client to retry
                response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                // Note: currently interpreting Retry-After as ms, not sec
                response.setHeader("Retry-After", "" + RETRY_AFTER_MILLISECONDS);
                return;
            }

            // de-serialize or create application context, store in session
            ApplicationContext ctx = getApplicationContext(request, memcache);

            super.service(request, response);

            // serialize
            started = new Date().getTime();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(ctx);
            oos.flush();
            byte[] bytes = baos.toByteArray();

            started = new Date().getTime();

            String id = AC_BASE + session.getId();
            Date expire = new Date(started
                    + (session.getMaxInactiveInterval() * 1000));
            Expiration expires = Expiration.onDate(expire);

            memcache.put(id, bytes, expires);

            DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
            Entity entity = new Entity(AC_BASE, id);
            entity.setProperty(PROPERTY_EXPIRES, expire.getTime());
            entity.setProperty(PROPERTY_DATA, new Blob(bytes));
            ds.put(entity);

        } catch (DeadlineExceededException e) {
            getLogger().warning("DeadlineExceeded for " + session.getId());
            sendDeadlineExceededNotification(request, response);
        } catch (NotSerializableException e) {
            getLogger().log(Level.SEVERE, "Not serializable!", e);

            // TODO this notification is usually not shown - should we redirect
            // in some other way - can we?
            sendNotSerializableNotification(request, response);
        } catch (Exception e) {
            getLogger().log(Level.WARNING,
                    "An exception occurred while servicing request.", e);

            sendCriticalErrorNotification(request, response);
        } finally {
            // "Next, please!"
            if (locked) {
                memcache.delete(mutex);
            }
            cleanSession(request);
        }
    }
View Full Code Here

public class WarmupServlet extends HttpServlet {
//  public void doGet(HttpServletRequest req, HttpServletResponse resp)
//      throws IOException {
  public void init() {
    // Using the synchronous cache
      MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
      syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
      //empty the entire cache before repopulating
      syncCache.clearAll();
    System.out.println("calling BloomCache");
    BloomFilter b = new BloomCache().getCachedBloomFilter();
    b.populate();
    System.out.println("calling TrieCache");
    new TrieCache().getCachedTrie("name_first");
View Full Code Here

  @SuppressWarnings("unchecked")
  public List<VideoSubmission> getVideoSubmissionsForArticle(String articleId,
      int limit, boolean moderated, String startIndex, boolean inverse) {

    boolean cacheable = false;
    MemcacheService ms = MemcacheServiceFactory.getMemcacheService();
    String cacheKey = "submissions-" + articleId;

    if (limit == DEFAULT_PAGE_SIZE && startIndex == null && !inverse && moderated) {
      cacheable = true;
      List<VideoSubmission> cached = (List<VideoSubmission>) ms.get(cacheKey);
      if (cached != null) {
        log.info("Cache hit for video submissions");
        return cached;
      }
    }

    PersistenceManager pm = PMF.get().getPersistenceManager();
    pm.setDetachAllOnCommit(true);
    ArrayList<VideoSubmission> submissions = new ArrayList<VideoSubmission>();
    Query query = pm.newQuery(VideoSubmission.class);

    try {
      query.setFilter("articleId == articleParam");
      if (moderated) {
        query.setFilter("status == statusParam");
      }
      if (startIndex != null) {
        if (inverse) {
          query.setFilter("createdIndex > startIndexParam");
        } else {
          query.setFilter("createdIndex <= startIndexParam");
        }
      }

      if (inverse) {
        query.setOrdering("createdIndex asc");
      } else {
        query.setOrdering("createdIndex desc");
      }

      HashMap params = new HashMap();
      params.put("articleParam", articleId);
      StringBuilder paramDec = new StringBuilder("String articleParam");
     
      if (moderated) {
        paramDec.append(", int statusParam");
        params.put("statusParam", VideoSubmission.ModerationStatus.APPROVED.ordinal());
      }
     
      if (startIndex != null) {
        paramDec.append(", String startIndexParam");
        params.put("startIndexParam", startIndex);
      }
     
      query.declareParameters(paramDec.toString());

      query.setRange(0, limit);
      List<VideoSubmission> results;
      results = (List<VideoSubmission>) query.executeWithMap(params);
      for (VideoSubmission submission : results) {
        submissions.add(submission);
      }

    } finally {
      query.closeAll();
      pm.close();
    }

    if (cacheable) {
      int cache_time = Integer.parseInt(System.getProperty(
          "com.google.tchotchke.ArticleSubmissionCacheTime", "60"));
      ms.put(cacheKey, submissions, Expiration.byDeltaSeconds(cache_time));
    }


    return submissions;
  }
View Full Code Here

   * when a new video is approved for an article.
   * @param articleId The article ID of the article that should have its
   *   memcache cache cleared.
   */
  public void clearMemcacheForArticle(String articleId) {
    MemcacheService ms = MemcacheServiceFactory.getMemcacheService();
    String cacheKey = "submissions-" + articleId;
    ms.delete(cacheKey);
  }
View Full Code Here

     * admin user.
     */
    private static final String _ADMIN_MESSAGE_KEY = "admin_message";

    public static void setAdminMessage(String message) {
        MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
        memcache.put(_ADMIN_MESSAGE_KEY, message);
    }
View Full Code Here

        MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
        memcache.put(_ADMIN_MESSAGE_KEY, message);
    }

    public static String getAndResetAdminMessage() {
        MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
        String message = (String) memcache.get(_ADMIN_MESSAGE_KEY);
        memcache.delete(_ADMIN_MESSAGE_KEY);
        return message;
    }
View Full Code Here

        PrintWriter out = resp.getWriter();

        List<String> headlines =
            new ArrayList(Arrays.asList("...", "...", "..."));

        MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();

        memcache.put("headlines", headlines);

        headlines = (List<String>) memcache.get("headlines");

        memcache.delete("headlines");

        memcache.put("headlines", headlines,
                     Expiration.byDeltaSeconds(300));

        memcache.put("headlines", headlines, null,
                     SetPolicy.ADD_ONLY_IF_NOT_PRESENT);

        boolean headlinesAreCached = memcache.contains("headlines");

        memcache.put("tempnode91512", "...");
        memcache.delete("tempnode91512", 5);
        memcache.put("tempnode91512", "..."); // fails within the 5 second add-lock

        Map<Object, Object> articleSummaries = new HashMap<Object, Object>();
        articleSummaries.put("article00174", "...");
        articleSummaries.put("article05234", "...");
        articleSummaries.put("article15280", "...");
        memcache.putAll(articleSummaries);

        List<Object> articleSummaryKeys = Arrays.<Object>asList(
            "article00174",
            "article05234",
            "article15820");
        articleSummaries = memcache.getAll(articleSummaryKeys);

        memcache.deleteAll(articleSummaryKeys);

        memcache.setNamespace("News");
        memcache.put("headlines", headlines);

        List<String> userHeadlines =
            new ArrayList(Arrays.asList("...", "...", "..."));
        memcache.setNamespace("User");
        memcache.put("headlines", userHeadlines);

        // Get User:"headlines"
        userHeadlines = (List<String>) memcache.get("headlines");

        // Get News:"headlines"
        memcache.setNamespace("News");
        headlines = (List<String>) memcache.get("headlines");

        memcache.put("work_done", 0);

        Long workDone = memcache.increment("work_done", 1);

        Stats stats = memcache.getStatistics();
        int ageOfOldestItemMillis = stats.getMaxTimeWithoutAccess();

        memcache.setErrorHandler(new StrictErrorHandler());

        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS");
        fmt.setTimeZone(new SimpleTimeZone(0, ""));
        out.println("<p>The time is: " + fmt.format(new Date()) + "</p>");
    }
View Full Code Here

TOP

Related Classes of com.google.appengine.api.memcache.MemcacheService

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.